How would you return a list of folders inside a directory? I just need their names. I know about glob.glob
to list everything in a directory but I don't know how to filter it.
Asked
Active
Viewed 105 times
2 Answers
3
You might combine list comprehension with some functions from os
to print folders inside current catalog following way:
import os
folders = [i for i in os.listdir(os.getcwd()) if os.path.isdir(i)]
print(folders)
where:
os.getcwd
gets current working directoryos.listdir
returns list of everything inside given directoryos.path.isdir
checks if i is directory
if you wish to do this for another catalog than current directory use os.chdir('path_to_your_catalog')
after import os
.

Daweo
- 31,313
- 3
- 12
- 25
2
You can do the following:
# Set root to whatever directory you want to check
root= os.getcwd()
dirlist = [ item for item in os.listdir(root) if os.path.isdir(os.path.join(root, item)) ]
print (dirlist)

CDJB
- 14,043
- 5
- 29
- 55