
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find TXT Files in Python Directory
Searching for specific files in a directory is a difficult task, and this can be accomplished by using different tools in Python.
In this article, we will see how to find all the files in a directory with an extension .txt using Python. Here are the different approaches, let's see one by one in detail -
Using os.listdir()
The os.listdir() is a function from Python's built-in os module which returns a list of names, i.e., as strings, of the entries in the directory given by the path.
Example
In this example, we will use the function in Python's os.listdir() to which we pass the path of the directory as the input parameter -
import os import os try: directory = r"D:\Tutorialspoint\Articles" # Change this to your target path txt_files = [file for file in os.listdir(directory) if file.endswith(".txt")] print("Text files in the directory:", txt_files) except FileNotFoundError: print("Directory does not exist.") except NotADirectoryError: print("That path is not a directory.")
Following is the output of the os.listdir() function, which is used to find the .txt files in the given directory -
Text files in the directory: ['sample.txt']
Using os.scandir()
The os.scandir() is a more powerful and efficient alternative to os.listdir(), especially when we need file metadata or want to filter by file type, such as .txt files.
Example
Here, in this example, we are replacing os.listdir() with os.scandir() to provide a more efficient way to list files in the directory in Python, and also using the try and exception to handle errors if the file or directory is not available.
import os import os try: directory = r"D:\Tutorialspoint\Articles" # Change this to your target path txt_files = [entry.name for entry in os.scandir(directory) if entry.is_file() and entry.name.endswith(".txt")] print("Text files in the directory:", txt_files) except FileNotFoundError: print("Directory does not exist.") except NotADirectoryError: print("That path is not a directory.")
Here is the output of the method os.scandir() to find the .txt files in the given directory -
Text files in the directory: ['sample.txt']
Recursive Search with os.walk()
The os.walk() is a built-in Python function from the os module that allows us to traverse a directory tree recursively. It walks through a directory and all its subdirectories by returning each directory's path, subdirectories, and files.
Example
In this example, we employ os.walk() method to achieve a recursive search to get .txt files along with the subdirectories -
import os import os try: directory = r"D:\Tutorialspoint\Articles" # Replace with your target directory txt_files = [] for root, dirs, files in os.walk(directory): for file in files: if file.endswith(".txt"): txt_files.append(os.path.join(root, file)) print("Text files in the directory: ",txt_files) except FileNotFoundError: print("Directory does not exist.") except NotADirectoryError: print("That path is not a directory.")
Here is the output of the method os.walk() used to get the .txt files -
Text files in the directory: ['D:\Tutorialspoint\Articles\sample.txt']
Using pathlib.Path()
The pathlib.Path is a modern object-oriented approach from the pathlib module in Python to work with filesystem paths. It allows us to traverse a directory tree recursively using the rglob() method, which is the cleanest way to search for files by pattern.
Example
In this example, we use the Path.rglob() method to achieve a recursive search to get .txt files along with the subdirectories -
from pathlib import Path try: directory = Path(r"D:\Tutorialspoint\Articles") # Replace with your target directory txt_files = list(directory.rglob("*.txt")) print("Text files in the directory: ", txt_files) except FileNotFoundError: print("Directory does not exist.") except NotADirectoryError: print("That path is not a directory.")
Here is the output of the method Path.rglob() used to get the .txt files -
Text files in the directory: [WindowsPath('D:/Tutorialspoint/Articles/sample.txt')]
Using glob.glob()
The glob.glob() is a function from Python's built-in glob module that finds all the pathnames that match a specified pattern according to the rules used by the Unix shell. It can be used for pattern matching file extensions such as .txt and supports recursive searches using the ** wildcard and recursive=True flag.
Example
In this example, we use glob.glob() method with the recursive flag to search through all subdirectories and list the .txt files -
import glob import glob try: directory = r"D:\Tutorialspoint\Articles" # Replace with your target directory pattern = directory + r"\**\*.txt" txt_files = glob.glob(pattern, recursive=True) print("Text files in the directory: ", txt_files) except Exception as e: print("An error occurred:", str(e))
Below is the output of the method glob.glob() used to get the .txt files -
Text files in the directory: ['D:\Tutorialspoint\Articles\sample.txt']
Whether we prefer simplicity, efficiency, or a modern approach, Python offers different powerful methods to find all .txt files in a directory. From the classic os.listdir() and efficient os.scandir(), to the recursive os.walk(), with pattern search using glob.glob() and the elegant pathlib.Path(), we have a variety of options to suit our specific needs.