Categories
Python Answers

How to iterate over files in a given directory with Python?

Spread the love

Sometimes, we want to iterate over files in a given directory with Python.

In this article, we’ll look at how to iterate over files in a given directory with Python.

How to iterate over files in a given directory with Python?

To iterate over files in a given directory with Python, we can use the os.listdir method.

For instance, we write:

import os

directory = os.fsencode('./')

for file in os.listdir(directory):    
    filename = os.fsdecode(file)
    if filename.endswith(".py"):
        print(os.path.join(directory.decode('utf-8'), filename))

We call os.fsencode with the directory string to create the directory byte string.

Then we call os.listdir with directory to loop through the entries in the directory.

Then we call os.fsdecode with file to get the filename of the file.

And then we call os.path.join with path segment strings to print the full path of each file.

Conclusion

To iterate over files in a given directory with Python, we can use the os.listdir 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 *