Reputation: 2070
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
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
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