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, os
os.chdir("/mydir")
for file in glob.glob("*.txt"):
print(file)
to change to the /mydir
directtory with
os.chdir("/mydir")
Then we get all the files with extension .txt in the folder and print the file names by writing
for file in glob.glob("*.txt"):
print(file)
Conclusion
To find all files in a directory with extension .txt in Python, we can use the glob.glob
method.