How to get a list of all sub-directories in the current directory using Python?


To get a list of all subdirectories in a directory, recursively, you can use the os.walk function. It returns a three tuple with first entry being all the subdirectories.

You can use it as follows:

import os
subdirs = [x[0] for x in os.walk('.')]
print(subdirs)

You can also list the directories(immediate only) using the os.listdir function and filtering the list using the os.path.isdir function.

For example

import os
d = '.'
subdirs = [os.path.join(d, o) for o in os.listdir(d) if os.path.isdir(os.path.join(d,o))]

Updated on: 16-Dec-2019

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements