Python Snippets

Directory Cleaner: Organize Files by Extension

This Python script organizes files in a directory by moving them into subfolders based on their file extensions. It’s useful for decluttering download folders, project directories, or any location where files tend to accumulate without organization.

import os
import shutil

def organize_files(directory: str):
    """Organize files in the specified directory by their extensions."""
    for filename in os.listdir(directory):
        filepath = os.path.join(directory, filename)
        
        # Skip directories
        if os.path.isdir(filepath):
            continue
            
        # Get file extension and create subfolder name
        _, ext = os.path.splitext(filename)
        ext = ext[1:].lower()  # Remove dot and normalize case
        
        if not ext:  # Handle files without extension
            ext = "no_extension"
            
        # Create subdirectory if it doesn't exist
        subdir = os.path.join(directory, ext)
        os.makedirs(subdir, exist_ok=True)
        
        # Move file to subdirectory
        new_path = os.path.join(subdir, filename)
        shutil.move(filepath, new_path)
        print(f"Moved: {filename} -> {ext}/")

if __name__ == "__main__":
    target_dir = input("Enter directory path to organize: ").strip()
    if os.path.isdir(target_dir):
        organize_files(target_dir)
        print("Organization complete!")
    else:
        print("Error: Invalid directory path")

Explanation:

  1. Functionality:
    • The script scans all files in the specified directory.
    • For each file, it extracts the extension (e.g., .txt, .jpg) and creates a corresponding subfolder if it doesn’t exist.
    • Files are then moved into their respective extension-based subfolders.
    • Files without extensions are placed in a no_extension folder.
  2. Why It’s Useful:
    • Automates file organization, saving time for users who deal with messy directories.
    • Works with any file type and handles edge cases (no extension, existing folders).
    • Lightweight and doesn’t require external dependencies.
  3. How to Run:
    • Save the script as directory_cleaner.py.
    • Run it with Python: python directory_cleaner.py.
    • When prompted, enter the full path to the directory you want to organize.

Note: Always back up important files before running automation scripts that move files.