Find All Files with Extension in Directory Python - Simple Guide
Use the
glob module or os module in Python to find all files with a specific extension in a directory. For example, glob.glob('path/*.txt') lists all text files in the given directory.Syntax
There are two common ways to find files with a specific extension in Python:
- Using
glob:glob.glob('directory_path/*.ext')returns a list of file paths matching the extension. - Using
osandos.path: Loop through files in a directory and check if their names end with the extension usingstr.endswith().
python
import glob # Using glob to find all .txt files files = glob.glob('path/to/directory/*.txt') # Using os to find all .txt files import os files = [f for f in os.listdir('path/to/directory') if f.endswith('.txt')]
Example
This example shows how to find all .py files in the current directory using glob and print their names.
python
import glob # Find all Python files in current directory python_files = glob.glob('*.py') for file in python_files: print(file)
Output
example.py
script.py
main.py
Common Pitfalls
Common mistakes when finding files by extension include:
- Not specifying the correct path, leading to empty results.
- Forgetting the dot in the extension (e.g., using
'txt'instead of'.txt'). - Using
os.listdir()without filtering for files only, which may include directories. - Not handling case sensitivity on some systems (e.g.,
.TXTvs.txt).
python
import os # Wrong: missing dot in extension files_wrong = [f for f in os.listdir('.') if f.endswith('txt')] # misses files ending with '.txt' # Right: include dot files_right = [f for f in os.listdir('.') if f.endswith('.txt')]
Quick Reference
Summary tips for finding files with extension:
- Use
glob.glob('path/*.ext')for simple pattern matching. - Use
os.listdir()withstr.endswith()for manual filtering. - Always include the dot in the extension (e.g.,
'.txt'). - Check if you want full paths (
glob) or just file names (os.listdir).
Key Takeaways
Use the glob module for easy file extension matching with patterns.
Always include the dot when specifying file extensions (e.g., '.txt').
os.listdir() requires manual filtering with str.endswith() to find files by extension.
Be aware of case sensitivity depending on your operating system.
Check your directory path carefully to avoid empty results.