How to list a directory tree in Python?

Sometimes, we want to list a directory tree in Python.

In this article, we’ll look at how to list a directory tree in Python.

How to list a directory tree in Python?

To list a directory tree in Python, we can use the os.walk method.

For instance, we write:

import os

for dirname, dirnames, filenames in os.walk('.'):
    for subdirname in dirnames:
        print(os.path.join(dirname, subdirname))

    for filename in filenames:
        print(os.path.join(dirname, filename))

We call os.walk with the root path string to return an iterator with tuples with dirname, dirnames, and filenames.

Then we can loop through dirnames and filenames and get the subdirectories and files in each directory respectively.

We call os.path.join to get the full subdirectory and file paths respectively.

Therefore, we get something like:

./.upm
./pyproject.toml
./poetry.lock
./test.csv
./art.png
./.breakpoints
./main.py
./.upm/store.json

from the print calls.

Conclusion

To list a directory tree in Python, we can use the os.walk method.