Count Files by Extension in Python
Count files in a directory grouped by file extension using Python's standard library.
Python code
16 linesfrom pathlib import Path
def count_files_by_extension(directory: str) -> dict[str, int]:
"""Count files in a directory grouped by file extension."""
data = {}
for path in Path(directory).iterdir():
if path.is_file():
ext = path.suffix.lower() or "(no extension)"
data[ext] = data.get(ext, 0) + 1
return data
if __name__ == "__main__":
result = count_files_by_extension(".")
for ext, count in sorted(result.items()):
print(f"{ext}: {count}")
print(f"\nTotal files: {sum(result.values())}")
Output
.py: 3
.txt: 2
(no extension): 1
Total files: 6
How it works
The function uses Path.iterdir() to iterate over all entries in the directory. For each entry that is a file, it extracts the lowercase suffix (extension) and updates the count in the dictionary using get with a default of 0, avoiding KeyErrors. This approach handles files without extensions by labeling them as (no extension). The final output uses sorted to display extensions in alphabetical order.
Common mistakes
- Using `path.is_file()` without checking for permission errors on some files.
- Forgetting to lowercase the suffix, causing case-sensitive counts like `.PY` vs `.py`.
- Using `path.suffix` on directories, which returns an empty string and adds a false `(no extension)` entry.
Variations
- Use `os.listdir()` and `os.path.isfile()` for a simpler but less modern approach.
- Use a `defaultdict(int)` to avoid explicit `get` calls.
Real-world use cases
- Inventorying project files to track code vs. documentation breakdown.
- Checking for stray files in a processed data directory before archival.
- Generating file-type statistics for a cleanup or migration script.
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.