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
Use os.walk(directory) to List Subdirectories
import os for x in os.walk("."): print(x)
In the above program, we invoked
os.walk(top) method to create a list of all directories contained in
To set the parent directory to the current directory of the script, we set
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
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)
This is how you can easily list subdirectories and folders using Python language.