How to List Files Matching a Glob Pattern in Python
Uses pathlib.Path.glob to find and sort all files matching a glob pattern like *.py in a directory.
Python code
15 linesfrom pathlib import Path
def list_files_matching(pattern: str, directory: str = ".") -> list[str]:
"""Return sorted list of file paths matching the glob pattern in a directory."""
return sorted(Path(directory).glob(pattern))
if __name__ == "__main__":
# Example: list all .py files in current directory
matches = list_files_matching("*.py")
for file_path in matches:
print(file_path)
if not matches:
print("No matching files found.")
Output
example.py
main.py
utils.py
How it works
Path.glob(pattern) returns an iterator of Path objects that match the pattern, and wrapping it in sorted() gives a deterministic, ordered list. The pattern *.py matches files in the directory but not subdirectories unless you use **/*.py. By default, the function searches the current directory, but you can pass any directory path. Path objects print as their string representation, which is the relative or absolute path depending on the input.
Common mistakes
- Using `glob.glob()` without sorting, which returns results in arbitrary order.
- Forgetting that `glob()` only matches files in the top directory unless you use `**/` for recursive matching.
- Not checking if the directory exists before calling `glob()`, which raises a `FileNotFoundError`.
Variations
- Use `Path.rglob(pattern)` for recursive matching through all subdirectories.
- Use `glob.glob(pattern)` from the `glob` module for a string-based approach.
Real-world use cases
- Discovering all test files matching `test_*.py` to run in a CI pipeline.
- Finding all CSV exports in a data landing directory for batch ingestion.
- Locating all `.log` files in an app directory for rotation or cleanup jobs.
Sponsored
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.