Categories
Python Answers

How to find all files in a directory with extension .txt in Python?

Spread the love

Sometimes, we want to find all files in a directory with extension .txt in Python.

In this article, we’ll look at how to find all files in a directory with extension .txt in Python.

How to find all files in a directory with extension .txt in Python?

To find all files in a directory with extension .txt in Python, we can use the glob.glob method.

For instance, we write:

import glob

for file in glob.glob("*.txt"):
    print(file)

We call glob.glob with '.txt' to find all the files with a path that ends with .txt

Then, we loop through the returned list with the for loop and print the file path in the loop body.

Conclusion

To find all files in a directory with extension .txt in Python, we can use the glob.glob 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 *