Find all the files in a directory with .txt extension in Python
In this tutorial, we will learn about finding all the files in a particular directory having a .txt extension using Python. Basically, a file having a .txt extension is a text file.
We can find all text files in a particular directory using three different methods in Python:
- listdir() method of the os module
- walk() method of the os module
- glob module
So let’s continue reading this article to check out each one with examples…
Using listdir() method of the os module
All the files in a directory with a particular extension can be found using the listdir() method of the os module in Python. The os.listdir() method is used to get the list of files and directories in the particular mentioned directory.
from os import listdir def list_of_files(dir_name,"txt"): return (f for f in listdir(dir_name) if file.endswith('.' + "txt"))
The endswith() method is a member of a string class that checks if a string ends with a certain suffix. Thus it will list all the files with .txt extension in the particular directory.
Using walk() method of the os module
We can find all the files in a directory by using the walk() method of the os module in Python. Also, this method can return the file name from a specific directory tree by walking the tree with top-down or bottom-up.
The walk() method of the module can recurse into subdirectories. Well, it can be avoided by returning on the first iteration of the loop.
from os import walk def list_of_files(dir_name,"txt"): for (dir_path,dir_name,file_names) in walk(dir_name): return (f for f in file_names if file.endswith('.'+ "txt"))
Using glob module
The glob module finds all the file names matching a specified pattern. This module is available for Python version 3.5+.
import os import glob def list_of_files(dir_name,"txt"): return f for f in glob.glob("*.txt")
Thus glob module can be used to find the files in a subdirectory with a particular file extension.