Reputation: 944
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.
Upvotes: 0
Views: 105
Reputation: 415
[ i[0] for i in os.walk('/tmp')]
This works because i[0] gives all the root paths as it will walk through them so we don't need to do join or anything.
Upvotes: 0
Reputation: 13049
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.
Upvotes: 3
Reputation: 144
Import os
#use os.walk()
Example:
For folder, sub, file in os.walk(path): Print(folder). #returns parent folder Print (sub). #returns sub_folder Print (file) # returns files
Upvotes: 0
Reputation: 944
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))]
Upvotes: 1