Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

How to Create a File Organizer That Sorts Files Automatically in Python

A Python script that scans a given folder, categorizes files by extension (Images, Documents, Audio, Video, Archives, Misc), and moves them into subfolders automatically.

Easy Python 3.6+ Jun 27, 2026 Automation & scripting 1 views 0 copies

Python code

38 lines
Python 3.6+
import os
import shutil
from pathlib import Path

FILE_CATEGORIES = {
    "Images": [".jpg", ".jpeg", ".png", ".gif", ".bmp"],
    "Documents": [".pdf", ".docx", ".txt", ".csv", ".xlsx"],
    "Audio": [".mp3", ".wav", ".flac", ".aac"],
    "Video": [".mp4", ".mkv", ".avi", ".mov"],
    "Archives": [".zip", ".tar", ".gz", ".rar"],
}

def organize_folder(folder_path):
    folder = Path(folder_path)
    if not folder.exists() or not folder.is_dir():
        print(f"Error: '{folder_path}' is not a valid directory.")
        return

    for item in folder.iterdir():
        if item.is_file():
            file_ext = item.suffix.lower()
            moved = False
            for category, extensions in FILE_CATEGORIES.items():
                if file_ext in extensions:
                    target_dir = folder / category
                    target_dir.mkdir(exist_ok=True)
                    shutil.move(str(item), str(target_dir / item.name))
                    print(f"Moved: {item.name} -> {category}/")
                    moved = True
                    break
            if not moved:
                misc_dir = folder / "Misc"
                misc_dir.mkdir(exist_ok=True)
                shutil.move(str(item), str(misc_dir / item.name))
                print(f"Moved: {item.name} -> Misc/")

if __name__ == "__main__":
    organize_folder("test_folder")

Output

stdout
Moved: photo.jpg -> Images/
Moved: report.pdf -> Documents/
Moved: song.mp3 -> Audio/
Moved: video.mp4 -> Video/
Moved: backup.zip -> Archives/
Moved: readme.txt -> Documents/

How it works

The script uses pathlib.Path for cross-platform path handling and iterates over all files in the specified directory. Each file's suffix is compared case-insensitively against a dictionary of extension lists. When a match is found, the corresponding category folder is created (if missing) and the file is moved via shutil.move. Unrecognized extensions fall into a 'Misc' folder. This approach is simple, readable, and avoids external dependencies.

Common mistakes

  • Forgetting to handle hidden files or system files (e.g., .DS_Store) that may also get moved.
  • Using `os.rename` instead of `shutil.move` which can fail across different filesystems or drives.
  • Not converting the file extension to lowercase, leading to missed matches like .JPG vs .jpg.

Variations

  1. Use `pathlib.Path.rglob('*.*')` to include files in nested subdirectories.
  2. Add a dry-run mode that only prints moves without actually moving files.

Real-world use cases

  • Cleaning up a cluttered Downloads folder by automatically sorting newly downloaded files.
  • Organizing photo archives from a camera SD card into date-based or type-based subfolders.
  • Processing incoming files in a shared network drive where employees upload mixed-format documents.

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.