How to Split Files by Extension in Python

Group files in a folder by their file extension into a dictionary using pathlib.

Easy Python 3.6+ Aug 9, 2026 Files & data 12 views 0 copies

Python code

25 lines
Python 3.6+
from 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

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

  1. Use `folder.glob('**/*')` with `rglob` instead of `iterdir()` to include files in subfolders.
  2. 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

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.