David542
David542

Reputation: 110093

Find all directories in a directory

Is there a method to find all directories in a given directory? I am trying the following, which gives me an empty list:

[item for item in os.listdir(dir) if os.path.isdir(item)]

Upvotes: 0

Views: 215

Answers (3)

David542
David542

Reputation: 110093

[item[0] for item in os.walk(dir)]

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798456

You forgot to use os.path.join() to join the directory to the entries.

Upvotes: 3

Luper Rouch
Luper Rouch

Reputation: 9492

os.listdir(dir) returns names relative to dir, you have to do something like:

[item for item in os.listdir(dir) if os.path.isdir(os.path.join(dir, item))]

Upvotes: 4

Related Questions