- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to find all files in a directory with extension .txt in Python?
You can use the os.listdir method to get all directories and files in a directory. Then filter the list to get only the files and check their extensions as well.
>>> import os >>> file_list = [f for f in os.listdir('.') if os.path.isfile(os.path.join('.', f)) and f.endswith('.txt')] >>> print file_list ['LICENSE.txt', 'NEWS.txt', 'README.txt']
The endswith method is a member of string class that checks if a string ends with a certain suffix.
You can also use the glob module to achieve the same:
>>> import glob, os >>> file_list = [f for f in glob.glob("*.txt")] >>> print file_list ['LICENSE.txt', 'NEWS.txt', 'README.txt']
- How to delete all files in a directory with Python?
- How to extract all the .txt files from a zip file using Python?
- How do I list all files of a directory in Python?
- How to list all files in a directory using Java?
- How to unzip all zipped files in a Linux directory?
- How to perform grep operation on all files in a directory?
- How to rename multiple files in a directory in Python?
- How to delete multiple files in a directory in Python?
- Java program to delete all the files in a directory recursively (only files)
- How to copy files with the specific extension in PowerShell?
- Java program to List all files in a directory recursively
- What is the best way to run all Python files in a directory?
- How to read data from all files in a directory using Java?
- How to list all files (only) from a directory using Java?
- How to get all the files, sub files and their size inside a directory in C#?