Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a list of all subdirectories in the current directory

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.

like image 308
Brad Zeis Avatar asked Jun 10 '09 02:06

Brad Zeis


People also ask

How do I list all subfolders in a directory?

Substitute dir /A:D. /B /S > FolderList. txt to produce a list of all folders and all subfolders of the directory. WARNING: This can take a while if you have a large directory.

What will show you all the subdirectory of the current directory?

Typing just "ls" will give you a list of all the files and subdirectories in the current directory.


1 Answers

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 subdirectories, recursively.

Note that the second entry in the tuple is the list of child directories of the entry in the first 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:

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

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

like image 124
Blair Conrad Avatar answered Sep 20 '22 19:09

Blair Conrad