Canard Bizar
Canard Bizar

Reputation: 1

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

Upvotes: 0

Views: 167

Answers (1)

Valerio Preti
Valerio Preti

Reputation: 353

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

Upvotes: 1

Related Questions