How can I get the list of folders in current working directory in Python?
I need only the folders, not files or sub-folders.
Asked
Active
Viewed 2,075 times
1

Alex L
- 8,748
- 5
- 49
- 75

Ahmet Sezgin Duran
- 23
- 3
-
http://stackoverflow.com/questions/141291/how-to-list-only-top-level-directories-in-python – ndpu Feb 11 '13 at 09:33
2 Answers
3
Simple list comprehension:
[fn for fn in os.listdir(u'.') if os.path.isdir(fn)]

nneonneo
- 171,345
- 36
- 312
- 383
0
Thanks to @ATOzTOA
You can use os.listdir
and os.path.isfile
like here:
import os
path = 'whatever your path is'
for item in os.listdir(path):
if not os.path.isfile(os.path.join(path, item)):
print "Folder: ",item
else:
print "File: ",item
Now you know what are folders and what are files.
Since you don't want files, you can simply store the folders (path or name) in a list
For that, Do this:
import os
path = 'whatever your path is'
folders = [] # list that will contain folders (path+name)
for item in os.listdir(path):
if not os.path.isfile(os.path.join(path, item)):
folders.append(os.path.join(path, item)) # os.path.join(path, item) is your folder path
-
@AhmetSezginDuran Added some more code, see that too. Also, pls accept this answer it it helped... – pradyunsg Feb 11 '13 at 10:09