How to Find Files by Extension in Python

This code walks a directory tree with pathlib, collects all file paths, and counts them by extension to summarize a project's contents.

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

Python code

24 lines
Python 3.9+
from pathlib import Path

def get_project_files(base_path="."):
    """Return a sorted list of all file paths under base_path."""
    base = Path(base_path)
    files = [p for p in base.rglob("*") if p.is_file()]
    return sorted(files)

def count_by_extension(files):
    """Return a dict mapping extension (lowercase) to file count."""
    counts = {}
    for f in files:
        ext = f.suffix.lower() or "no_extension"
        counts[ext] = counts.get(ext, 0) + 1
    return counts

if __name__ == "__main__":
    files = get_project_files(".")
    print(f"Total files: {len(files)}")
    for ext, count in sorted(count_by_extension(files).items()):
        print(f"{ext}: {count}")
    print("\nFirst 5 files:")
    for f in files[:5]:
        print(f)

Output

stdout
Total files: 12
.md: 2
.py: 5
.txt: 3
no_extension: 2

First 5 files:
README.md
setup.py
src/main.py
src/utils.py
tests/test_app.py

How it works

The Path.rglob method recursively matches all files and directories, with is_file() filtering out folders. Using a list comprehension keeps the code concise and readable. The suffix property returns the file extension including the dot, and lowercasing it ensures consistent grouping. The get method with a default of 0 avoids KeyError when incrementing counts. Sorting the final list makes output deterministic, which is helpful for testing and reproducibility.

Common mistakes

  • Forgetting to call `.is_file()` so directories are included in the results
  • Not lowercasing extensions, causing `.PY` and `.py` to count separately
  • Assuming the count dict preserves insertion order without sorting when printing

Variations

  1. Use `os.walk` from the standard library instead of pathlib for older Python versions
  2. Use `collections.Counter` to replace the manual counting loop

Real-world use cases

  • Summarizing a codebase before a refactor to understand file type distribution.
  • Building a cleanup script that identifies orphaned or duplicate files by extension.
  • Generating a manifest of project files for packaging or deployment artifacts.

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.