Use Path.glob("*.txt") from Python’s built-in pathlib module (or Path.rglob("*.txt") to include subdirectories) to locate all .txt files in a directory cleanly across Windows, macOS, and Linux.
Basic Example
from pathlib import Path
# 1. Target directory (use "." for the current working directory)
folder = Path("/path/to/directory")
# 2. Find all .txt files in the top-level directory only
txt_files = list(folder.glob("*.txt"))
# 3. Find all .txt files recursively across all subdirectories
all_txt_files = list(folder.rglob("*.txt"))
for file_path in txt_files:
print(file_path.name) # e.g., "notes.txt"
Key Details & Alternative Methods
- Lazy iterator vs. list: Both
.glob()and.rglob()return generator iterators that yieldPathobjects on demand—ideal for large directories. Wrap them inlist(...)only when you need all paths in memory at once. - Case-insensitive matching (Linux/macOS): On Linux,
*.txtwill miss files ending in.TXT. To match any casing across all operating systems, filter by.suffix.lower():txt_files = [ p for p in folder.iterdir() if p.is_file() and p.suffix.lower() == ".txt" ] - Using the
globmodule (string paths): If your codebase prefers plain strings overPathobjects, useglob.glob()from the built-inglobmodule:import glob # Top-level only files = glob.glob("/path/to/directory/*.txt") # Recursive search recursive_files = glob.glob("/path/to/directory/**/*.txt", recursive=True) - Using
os.listdir()oros.walk(): Useful when working with legacy codebases or when you already traverse directory trees withos.walk().
Comparison of File-Finding Methods
| Method | Return Type | Recursive Support | Best Used When |
|---|---|---|---|
Path.glob("*.txt") |
Iterator of Path objects |
Use .rglob("*.txt") or **/*.txt |
Modern Python 3 codebases (cleanest, cross-platform). |
glob.glob("*.txt") |
list of str paths |
Pass recursive=True with ** |
You specifically need string paths without Path conversion. |
os.listdir() + .endswith() |
list of filenames (str) |
No (use os.walk() instead) |
Simple flat directory checks without pattern matching. |
You must log in or register to comment.
