[英]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.isdir
和os.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.