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 yield Path objects on demand—ideal for large directories. Wrap them in list(...) only when you need all paths in memory at once.
  • Case-insensitive matching (Linux/macOS): On Linux, *.txt will 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 glob module (string paths): If your codebase prefers plain strings over Path objects, use glob.glob() from the built-in glob module:
    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() or os.walk(): Useful when working with legacy codebases or when you already traverse directory trees with os.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.