How to Group Files by Extension in Python

Group file names by their file extension using a dictionary and pathlib, producing a simple clear mapping for beginners.

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

Python code

24 lines
Python 3.9+
from pathlib import Path


def group_data_by_extension(files: list[Path]) -> dict[str, list[str]]:
    """Group file names by their extension."""
    grouped: dict[str, list[str]] = {}
    for file in files:
        ext = file.suffix.lower()
        grouped.setdefault(ext, []).append(file.name)
    return grouped


if __name__ == "__main__":
    files = [
        Path("report.pdf"),
        Path("photo.jpg"),
        Path("notes.txt"),
        Path("presentation.pdf"),
        Path("image.png"),
        Path("readme.txt"),
    ]
    result = group_data_by_extension(files)
    for ext in sorted(result):
        print(f"{ext}: {result[ext]}")

Output

stdout
.jpg: ['photo.jpg']
.png: ['image.png']
.pdf: ['report.pdf', 'presentation.pdf']
.txt: ['notes.txt', 'readme.txt']

How it works

The function takes a list of pathlib.Path objects and uses the suffix property to extract each file's extension. setdefault initializes a list for a new extension if it doesn't exist, then appends the filename to that list. This avoids manual if ext in grouped checks and keeps the code concise. Using lowercase extensions ensures grouping is case-insensitive, which is common in production file handling.

Common mistakes

  • Using `file.name` but forgetting that `suffix` includes the dot, like '.txt'
  • Not lowering the extension, causing '.PDF' and '.pdf' to split into two groups
  • Modifying the input list because Path objects are mutable references

Variations

  1. Use `collections.defaultdict(list)` for automatic key initialization
  2. Group by extension separately using a dict comprehension with conditional logic

Real-world use cases

  • Organizing downloaded files into folders by type (images, PDFs, text) for cleanup scripts.
  • Reviewing a server directory to count file types before building a report for stakeholders.
  • Filtering or validating uploaded files in a web app by grouping accepted extensions.

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.