Categories
Python Answers

How to get a directory-tree listing in Python?

Spread the love

Sometimes, we want to get a directory-tree listing in Python.

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

How to get a directory-tree listing in Python?

To get a directory-tree listing 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))

to call os.walk with '.' to return an iterator with the directories and files in the folder.

It traverses the whole directory tree and returns items from all levels.

In the loop, we print out all the child directories with

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

And we print out all the child file paths with

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

Conclusion

To get a directory-tree listing in Python, we can use the os.walk method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *