Sometimes, we want to get a list of all subdirectories in the current directory with Python.
In this article, we’ll look at how to get a list of all subdirectories in the current directory with Python.
How to get a list of all subdirectories in the current directory with Python?
To get a list of all subdirectories in the current directory with Python, we can use the os.walk
method.
For instance, we write:
import os
directory = '/'
dirs = [x[0] for x in os.walk(directory)]
print(dirs)
We call os.walk
with the directory
path to return an iterator with the tuples containing the directory path strings.
Then we can get them get the directory path string from each tuple with x[0]
.
Therefore, dirs
is something like ['./', './.upm']
.
Conclusion
To get a list of all subdirectories in the current directory with Python, we can use the os.walk
method.