Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python脚本在当前目录下工作,但在指定目录时不工作_Python_Python 3.x - Fatal编程技术网

Python脚本在当前目录下工作,但在指定目录时不工作

Python脚本在当前目录下工作,但在指定目录时不工作,python,python-3.x,Python,Python 3.x,当我尝试打印内容时,其他位置的工作也是如此 但是,当我希望文件也显示其大小时,它只在当前路径中起作用 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 f

当我尝试打印内容时,其他位置的工作也是如此

但是,当我希望文件也显示其大小时,它只在当前路径中起作用

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
时,请不要找到该文件的引用

您应该通过以下方式更正脚本:

导入操作系统
导入系统
#检查是否提供了路径
#否则请使用当前位置
arg_list=len(sys.argv)-1
如果参数列表!=1:
路径='。'
elif arg_list==1:
path=sys.argv[1]
#列出文件和目录
#如果它是一个文件,也显示它的大小
catalog=os.listdir(路径)
对于目录中的项目:

file=os.path.join(path,item)#其他目录的文件大小显示会发生什么变化?
os.path.join()
比+'\'+更好。