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.
Python code
24 linesfrom 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
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
- Use `os.walk` from the standard library instead of pathlib for older Python versions
- 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
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.