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

PythonServer Side ProgrammingProgramming

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))]
raja
Published on 27-Dec-2017 07:34:19
Advertisements