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.
Python code
24 linesfrom 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
.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
- Use `collections.defaultdict(list)` for automatic key initialization
- 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
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.