簡體   English   中英

Python 腳本在當前目錄中有效,但在指定時無效

[英]Python script works in current directory but not when one is specified

當我嘗試只打印內容時,在其他位置也可以使用。

但是當我希望文件也顯示它們的大小時,它只能在當前路徑中工作。

import os
import sys

#check if a path is provided
#else use the current loction
arg_list = len(sys.argv) -1

if arg_list != 1:
    path = '.' 
elif arg_list == 1:
    path = sys.argv[1]

#list the files and directorys
#if it is a file also show it's size
catalog = os.listdir(path)

for item in catalog:
    #just print() here works also for other directories
    if os.path.isdir(item):
        print(f'    {item}')

    elif os.path.isfile(item):
        size = os.path.getsize(item)
        print(f'{size} {item}')

此指令: catalog = os.listdir(path)返回給定目錄中的文件/文件夾列表,沒有完整路徑,只有名稱。

因此,當您嘗試更改文件夾os.path.isdiros.path.isfile ,找不到對該文件的引用。

您應該以這種方式更正您的腳本:

import os
import sys

#check if a path is provided
#else use the current loction
arg_list = len(sys.argv) -1

if arg_list != 1:
    path = '.' 
elif arg_list == 1:
    path = sys.argv[1]

#list the files and directorys
#if it is a file also show it's size
catalog = os.listdir(path)

for item in catalog:
    file = os.path.join(path, item) # <== Here you set the correct name with the full path for the file
    #just print() here works also for other directories
    if os.path.isdir(file):  # <== then change the reference here
        print(f'    {item}')

    elif os.path.isfile(file):  # <== here 
        size = os.path.getsize(file)  # <== and finally here
        print(f'{size} {item}')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM