Find all files in a directory with extension .txt in Python
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
In Python, working with files and directories is a common task, particularly when dealing with large datasets or when performing file manipulation tasks. When you need to find all the files in a directory with a specific extension (e.g., .txt), Python's standard library provides several tools to assist you. The most commonly used modules for interacting with the filesystem are os and pathlib. Here, we'll explore how to use these modules to find all .txt files in a specified directory.
Using the os Module
The os module includes versatile utilities to interact with the operating system. os.listdir() and os.path are particularly useful for directory and file manipulation.
Example with os:
This code lists all files in the specified directory, checks if they end with the .txt extension, and adds them to the txt_files list.
Using the pathlib Module
Introduced in Python 3.4, pathlib offers a more intuitive approach to handle filesystem paths. It provides an object-oriented way to manage file system paths.
Example with pathlib:
Path.glob() method is used for pattern matching, and *.txt effectively finds all .txt files in the directory.
Comparing os and pathlib
Below is a table comparing the use of os and pathlib for finding .txt files in a directory:
| Feature | os Module | pathlib Module |
| Approach | Procedural | Object-Oriented |
| Line of code | More | Less |
| Readability | Lower | Higher |
| Pattern Matching | Manual check | Built-in with glob method |
Additional Considerations
- Recursively Finding Files: To find files not only in the specified directory but also in all subdirectories, you can modify the
globmethod inpathlibto**/*.txtor useos.walk()in theosmodule. - Error Handling: It's good practice to add error handling when dealing with file operations to handle situations like permission errors or non-existent directories.
- Performance: For directories with a very large number of files, consider performance implications of each approach.
Conclusion
Both os and pathlib provide robust solutions for locating files with a specific extension in Python, with pathlib generally offering a more modern and easy-to-use API. The choice between using os or pathlib can depend on personal preference or specific project requirements regarding readability and code maintainability.
Related reading
- Find all files in a directory with extension .txt in Python
- Find all packages installed with easy_install/pip?
- Find and replace string values in list
- Find difference between two data frames
- Find elements in one list that are not in the other
- Find element's index in pandas Series
- Find first sequence item that matches a criterion
- Find full path of the Python interpreter Python executable?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.