Count Files by Extension in Python

Count files in a directory grouped by file extension using Python's standard library.

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

Python code

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

stdout
.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

  1. Use `os.listdir()` and `os.path.isfile()` for a simpler but less modern approach.
  2. 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

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.