0

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.

1
  • Recursively or just at the first level? Commented Jun 22, 2020 at 22:07

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

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.
Thanks for the comment. I was not aware of this.
0

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

Comments

0
[ i[0] for i in os.walk('/tmp')] 
  1. here '/tmp' is the directory path for which all directories are listed
  2. you need to import os

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.