Sometimes, we want to use os.walk() to recursively traverse directories in Python.
In this article, we’ll look at how to use os.walk() to recursively traverse directories in Python.
How to use os.walk() to recursively traverse directories in Python?
To use os.walk() to recursively traverse directories in Python, we call os.walk with the root directory.
For instance, we write
import os
for root, dirs, files in os.walk("."):
path = root.split(os.sep)
print(os.path.basename(root))
for file in files:
print(file)
to call os.walk with the root directory that we want to traverse.
Then we loop through the dirs directories and files files with a for loop.
We get the split path with the string split method called with the path separator os.sep.
And we print the base folder name of root with basename.
Then we loop through the files in the directory with another for loop.
Conclusion
To use os.walk() to recursively traverse directories in Python, we call os.walk with the root directory.