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.
So when you try to change folder os.path.isdir
and os.path.isfile
don't find the reference to that file.
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}')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.