Summary: In this tutorial, you will learn to list subdirectories using the Python programming language.

Listing subdirectories lists all directories contained in a parent directory along with the parent directory.

In Python, you can easily list subdirectories using the os.walk(directory) method.

Use os.walk(directory) to List Subdirectories

import os

for x in os.walk("."):
    print(x[0])

Output:

.
./folder1
./folder2

In the above program, we invoked os.walk(top) method to create a list of all directories contained in top.

To set the parent directory to the current directory of the script, we set top to ".".

In return, we get a generator consisting of tuples each of length 3.

The first element in each tuple is the name of the directory, the second element is a list of subdirectories in the directory, and the third element is a list of files in the directory.

To only see the folders contained in the directory, we have accessed the first element of each tuple generated by os.walk().

If you wish to list child subdirectories of the folders, you can access the second element of the tuple as follows:

for x in os.walk("."):
    print(x[1])

This is how you can easily list subdirectories and folders using Python language.

Adarsh Kumar

I am an engineer by education and writer by passion. I started this blog to share my little programming wisdom with other programmers out there. Hope it helps you.

Leave a Reply