
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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.
For example
>>> 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']
- Related Articles
- 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?
- How to copy files with the specific extension in PowerShell?
- 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?
- Java program to delete all the files in a directory recursively (only files)
- Java program to List all files in a directory recursively
- Golang program to get all files present in a directory
- How to get all the files, sub files and their size inside a directory in C#?

Advertisements