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.

Easy Python 3.9+ Aug 9, 2026 Files & data 12 views 0 copies

Python code

15 lines
Python 3.9+
from 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

stdout
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

  1. Use `Path.rglob(pattern)` for recursive matching through all subdirectories.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.