haxtar
haxtar

Reputation: 2070

os.path.isdir() not recognizing directories when path is not current directory

I have a list of directories (purple, blue, red) to be recognized in a main directory called colors.

When I run this script from within colors:

path_to_folders = './'
folders = [f for f in os.listdir(path_to_folders) if os.path.isdir(f)]
print(folders)

I get the list of folders:

['purple', 'blue', 'red']

When I set 'path_to_folders = '../colors' and run the script from outside of the colors directory, the directories encompassed within it are not recognized as directories, even though they are read in as f.

The list of folders is empty: [], but printing each f gives:

purple
blue
red

How can this be?

Upvotes: 1

Views: 1770

Answers (2)

blhsing
blhsing

Reputation: 107124

os.path.listdir() returns just the file names, without path names, while os.path.isdir() requires the full path name, so you should use os.path.join() to prepend the path name to the file names:

folders = [f for f in os.listdir(path_to_folders) if os.path.isdir(os.path.join(path_to_folders, f))]

Upvotes: 2

wizzwizz4
wizzwizz4

Reputation: 6426

Without ../ at the beginning, those folders will be treated as though they're in the CWD. No such folders in the CWD exist. Adjust your code so:

path_to_folders = './'
folders = [f for f in os.listdir(path_to_folders) if os.path.isdir(path_to_folders . f)]
print(folders)

Upvotes: 1

Related Questions