This post will discuss how to list all subdirectories in a directory in Python.

1. Using os.listdir() function

A simple solution to list all subdirectories in a directory is using the os.listdir() function. However, this returns the list of all files and subdirectories in the root directory. You can filter the returned list using the os.path.isdir() function to list only the subdirectories.

Download Code

 
You can easily extend the solution to search within subdirectories as well, as shown below:

Download Code

2. Using os.scandir() function

With Python 3.5, you can use the os.scandir() function, which offers significantly better performance over os.listdir(). It returns directory entries along with file attribute information. To filter the returned entries to exclude files, call the is_dir() function, which returns True if the current entry is a directory or a symbolic link pointing to a directory.

Download Code

 
You can easily make the above code recursive to enable search within subdirectories:

Download Code

3. Using pathlib module

You can also use the pathlib module with Python 3.4 to list all subdirectories in a directory. The idea is to call the Path.iterdir() function, yielding path objects of the directory contents. You can filter the returned objects for directories or a symbolic link pointing to a directory, use the Path.is_dir()() function.

Download Code

 
Here’s the recursive version, which also searches within the subdirectories:

Download Code

4. Using os.walk() function

To search in subdirectories, consider using the os.walk() function. It recursively yields a 3-tuple (dirpath, dirnames, filenames), where dirpath is the path to the current directory, dirnames is a list of the names of the subdirectories in the current directory and filenames lists the regular files in the current directory.

Download Code

5. Using glob module

Finally, you can use the glob.glob function, which returns an iterator over the list of pathnames that match the specified pattern.

Download Code

 
Python 3.5 extended support for recursive globs using ** to search subdirectories and symbolic links to directories.

Download Code

That’s all about listing all subdirectories in a directory in Python.