Categories
JavaScript Answers Python Answers

How to list all files of a directory with Python?

Spread the love

Sometimes, we want to list all files of a directory with Python.

In this article, we’ll look at how to list all files of a directory with Python.

How to list all files of a directory with Python?

To list all files of a directory with Python, we can use the os.walk method.

For instance, we write:

from os import walk

f = []
for (dirpath, dirnames, filenames) in walk('./'):
    f.extend(filenames)

print(f)

We use the walk method with the root path to list everything from the root path and down.

dirpath is the directory path.

dirname is an array of directory names.

filenames is an array of file names.

We use f.extend to put the filenames entries into f.

Conclusion

To list all files of a directory with 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 *