Python Snippets

Automatic File Organizer by File Type and Date

This Python script automatically organizes files in a specified directory by creating subfolders based on file extensions and modification dates. It’s particularly useful for decluttering download folders, organizing project files, or maintaining a structured file system.

import os
import shutil
from pathlib import Path
from datetime import datetime

def organize_files_by_type_and_date(source_dir, destination_dir=None):
    """
    Organizes files in source_dir by file extension and modification date.
    
    Args:
        source_dir (str): Path to the directory containing files to organize
        destination_dir (str, optional): Path to organize files into. 
                                         Defaults to source_dir if not provided.
    """
    source_path = Path(source_dir)
    
    if not source_path.exists():
        raise FileNotFoundError(f"Source directory '{source_dir}' does not exist")
    
    if destination_dir is None:
        destination_path = source_path
    else:
        destination_path = Path(destination_dir)
        destination_path.mkdir(parents=True, exist_ok=True)
    
    # Supported file categories
    file_categories = {
        'images': ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.svg'],
        'documents': ['.pdf', '.doc', '.docx', '.txt', '.rtf', '.odt'],
        'spreadsheets': ['.xlsx', '.xls', '.csv', '.ods'],
        'presentations': ['.ppt', '.pptx', '.odp'],
        'videos': ['.mp4', '.avi', '.mkv', '.mov', '.wmv'],
        'audio': ['.mp3', '.wav', '.flac', '.aac', '.ogg'],
        'archives': ['.zip', '.rar', '.7z', '.tar', '.gz'],
        'programs': ['.exe', '.msi', '.bat', '.sh'],
        'code': ['.py', '.js', '.html', '.css', '.java', '.cpp', '.c']
    }
    
    organized_count = 0
    
    # Process each file in the source directory
    for item in source_path.iterdir():
        if item.is_file():
            # Get file extension
            file_ext = item.suffix.lower()
            
            # Determine category
            category = 'others'
            for cat, extensions in file_categories.items():
                if file_ext in extensions:
                    category = cat
                    break
            
            # Get modification date
            mod_time = datetime.fromtimestamp(item.stat().st_mtime)
            date_folder = mod_time.strftime("%Y-%m-%d")
            
            # Create destination path
            dest_folder = destination_path / category / date_folder
            dest_folder.mkdir(parents=True, exist_ok=True)
            
            # Move file
            destination = dest_folder / item.name
            if not destination.exists():
                shutil.move(str(item), str(destination))
                organized_count += 1
                print(f"Moved: {item.name} -> {destination}")
            else:
                print(f"Skipped (already exists): {item.name}")
    
    print(f"\nOrganization complete! {organized_count} files organized.")

# Example usage
if __name__ == "__main__":
    # Organize files in the current directory
    # organize_files_by_type_and_date(".")
    
    # Or organize files from downloads to a specific organized folder
    # organize_files_by_type_and_date("~/Downloads", "~/Organized_Files")
    
    # For demonstration, organize files in a test directory
    test_dir = "test_organize"
    os.makedirs(test_dir, exist_ok=True)
    
    # Create some test files
    test_files = [
        "document.pdf",
        "image.jpg",
        "spreadsheet.xlsx",
        "presentation.pptx",
        "script.py",
        "archive.zip"
    ]
    
    for filename in test_files:
        with open(os.path.join(test_dir, filename), "w") as f:
            f.write("Test content")
    
    print("Organizing test files...")
    organize_files_by_type_and_date(test_dir)

Explanation

This script automatically organizes files in a directory by:

  1. File Type Categorization - Files are sorted into logical categories like documents, images, videos, etc., based on their extensions
  2. Date-based Subfolders - Within each category, files are further organized into subfolders named after their modification date (YYYY-MM-DD format)
  3. Intelligent Handling - The script skips files that would overwrite existing ones and provides feedback on actions taken

Why This Is Useful

How to Run

  1. Save the code to a file (e.g., file_organizer.py)
  2. Modify the example usage section at the bottom:
    • To organize the current directory: organize_files_by_type_and_date(".")
    • To organize a specific directory: organize_files_by_type_and_date("/path/to/source")
    • To organize files into a different destination: organize_files_by_type_and_date("/path/to/source", "/path/to/destination")
  3. Run with: python file_organizer.py

The script will create a folder structure like:

destination/
├── documents/
│   ├── 2026-01-05/
│   └── 2026-01-07/
├── images/
│   └── 2026-01-07/
└── ...