简体   繁体   English

Python 脚本在当前目录中有效,但在指定时无效

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

When I try to just print the content is work in other locations as well.当我尝试只打印内容时,在其他位置也可以使用。

But when I want files to show their size as well, it only works in the current path.但是当我希望文件也显示它们的大小时,它只能在当前路径中工作。

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}')

This instruction: catalog = os.listdir(path) return the list of the files/folders inside the given directory without their full path, just the name.此指令: catalog = os.listdir(path)返回给定目录中的文件/文件夹列表,没有完整路径,只有名称。

So when you try to change folder os.path.isdir and os.path.isfile don't find the reference to that file.因此,当您尝试更改文件夹os.path.isdiros.path.isfile ,找不到对该文件的引用。

You should correct your script in this way:您应该以这种方式更正您的脚本:

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