Mini Project: File Organizer Script
Build a file organizer that sorts files into folders by type. Combines file handling, os/pathlib, and exception handling.
20 min•By Priygop Team•Updated 2026
File Organizer
File Organizer
import os
from pathlib import Path
from collections import defaultdict
# File type categories
FILE_TYPES = {
"Images": [".jpg", ".jpeg", ".png", ".gif", ".svg", ".webp"],
"Documents": [".pdf", ".doc", ".docx", ".txt", ".xlsx", ".pptx"],
"Videos": [".mp4", ".avi", ".mkv", ".mov"],
"Audio": [".mp3", ".wav", ".flac", ".aac"],
"Code": [".py", ".js", ".ts", ".html", ".css", ".json"],
"Archives": [".zip", ".rar", ".7z", ".tar", ".gz"],
}
def get_category(extension):
"""Get file category based on extension."""
ext = extension.lower()
for category, extensions in FILE_TYPES.items():
if ext in extensions:
return category
return "Other"
def organize_files(directory):
"""Organize files in a directory by type."""
path = Path(directory)
if not path.exists():
print(f"Directory not found: {directory}")
return
# Count files by category
stats = defaultdict(list)
for item in path.iterdir():
if item.is_file():
category = get_category(item.suffix)
stats[category].append(item.name)
# Display organization plan
print(f"\n=== File Organization Plan ===")
print(f"Directory: {path.resolve()}")
print(f"Total files: {sum(len(f) for f in stats.values())}\n")
for category in sorted(stats.keys()):
files = stats[category]
print(f"📁 {category}/ ({len(files)} files)")
for f in sorted(files)[:5]:
print(f" 📄 {f}")
if len(files) > 5:
print(f" ... and {len(files) - 5} more")
return stats
# Demo with simulated files
print("=== File Organizer Demo ===\n")
# Simulate file categorization
test_files = [
"photo.jpg", "report.pdf", "script.py",
"song.mp3", "video.mp4", "archive.zip",
"readme.txt", "style.css", "data.json",
"image.png", "notes.docx", "app.js"
]
stats = defaultdict(list)
for f in test_files:
ext = Path(f).suffix
cat = get_category(ext)
stats[cat].append(f)
for cat in sorted(stats.keys()):
print(f"📁 {cat}/")
for f in sorted(stats[cat]):
print(f" 📄 {f}")
print()
print(f"Total: {len(test_files)} files → {len(stats)} folders")Tip
Tip
Use shutil.move() for safe file moving with error handling. Combine pathlib and os for powerful file management scripts.
Diagram
Loading diagram…
Everything in Python is an object — use type() to check
Common Mistake
Warning
Not handling file permission errors. Always wrap file operations in try/except PermissionError.
Practice Task
Note
(1) Build a script that sorts files by extension. (2) Add duplicate detection. (3) Create a backup before moving.