How to Split Files by Extension in Python
Group files in a folder by their file extension into a dictionary using pathlib.
Python code
25 linesfrom pathlib import Path
def split_files_by_extension(folder_path):
folder = Path(folder_path)
files_by_ext = {}
for file_path in folder.iterdir():
if file_path.is_file():
ext = file_path.suffix.lower() or "no_extension"
files_by_ext.setdefault(ext, []).append(file_path.name)
return files_by_ext
if __name__ == "__main__":
data_dir = Path("sample_data")
data_dir.mkdir(exist_ok=True)
sample_files = ["report.txt", "notes.txt", "data.csv", "image.png", "script.py", "README"]
for name in sample_files:
(data_dir / name).write_text("sample content")
result = split_files_by_extension(data_dir)
for ext, files in sorted(result.items()):
print(f"{ext} -> {files}")
Output
.csv -> ['data.csv']
.png -> ['image.png']
.py -> ['script.py']
.txt -> ['notes.txt', 'report.txt']
no_extension -> ['README']
How it works
Path.iterdir() yields all entries in the folder, and we filter with is_file() so directories are skipped. file_path.suffix returns the extension including the dot (e.g., .txt), and or "no_extension" handles files without an extension by defaulting to a readable key. setdefault(ext, []).append(...) creates a new list for each extension the first time it's seen, then appends subsequent filenames. Using sorted(result.items()) makes the output deterministic, which is handy for scripting and tests.
Common mistakes
- Forgetting to call `is_file()` and accidentally grouping directories as files.
- Not lowercasing extensions, so `Report.TXT` and `report.txt` land in different groups.
- Assuming `suffix` includes the dot, then writing keys like `txt` instead of `.txt`.
Variations
- Use `folder.glob('**/*')` with `rglob` instead of `iterdir()` to include files in subfolders.
- Return full `Path` objects instead of names if you need to open the files later.
Real-world use cases
- Organizing exported downloads into folders by type before further processing, like separating CSVs from images.
- Building a cleanup job that deletes or archives files based on extension rules.
- Preparing a file inventory report that lists counts per extension for storage audits.
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.