tags:

views:

514

answers:

3

Is there a way to return a list of all the subdirectories in the current directory in python?

I know you can do this with files, but I need to get the list of directories instead.

+5  A: 

Do you mean immediate subdirectories, or every directory right down the tree?

Either way, you could use os.walk to do this:

os.walk(directory)

will yield a tuple for each subdirectory. Ths first entry in the 3-tuple is a directory name, so

[x[0] for x in os.walk(directory)]

should give you all of the directories.

Note that the 2nd entry in the tuple is the list of child directories of the entry in the 1st position, so you could use this instead, but it's not likely to save you much.

However, you could use it just to give you the immediate child directories:

os.walk('.').next()[1]

Or see the other solutions already posted, using os.listdir and os.path.isdir, including those at get all of the immediate subdirectories in python.

Blair Conrad
love the os.walk().next() answer. +1
Triptych
I think os.walk returns triples (root,dirs,files). Which means that dirs has many repeating entries. Is there a more efficient way that recurses through directories?
mathtick
@mathtick, dirs won't have repeats - just one entry per subdirectory
Blair Conrad
+3  A: 

If you need a recursive solution that will find all the subdirectories in the subdirectories, use walk as proposed before.

If you only need the current directory's child directories, combine os.listdir with os.path.isdir

Eli Bendersky
+6  A: 
import os
import os.path
[o for o in os.listdir('.') if os.path.isdir(o)]
gahooa