I would like to know if there's a quick 1 line of code to list all the directories in a directory. It's similar to this question: How do I list all files of a directory? , but with folders instead of files.
4 Answers
Here is a recipe for just the first level:
dname = '/tmp' [os.path.join(dname, d) for d in next(os.walk(dname))[1]] and a recursive one:
dname = '/tmp' [os.path.join(root, d) for root, dirs, _ in os.walk(dname) for d in dirs] (after import os, obviously)
Note that on filesystems that support symbolic links, any links to directories will not be included here, only actual directories.
Comments
Using os.listdir to list all the files and folders and os.path.isdir as the condition:
import os cpath = r'C:\Program Files (x86)' onlyfolders = [f for f in os.listdir(cpath) if os.path.isdir(os.path.join(cpath, f))] 2 Comments
alani
Probably worth noting here that this includes any symbolic links to directories. This behaviour contrasts with the version based on
os.walk which I posted, which excludes them. The question is not explicit about which behaviour is required, but users should be aware of the difference.Brad123
Thanks for the comment. I was not aware of this.