Python Auto-Organize your downloads folder

Because it's a real big mess

Yes, you open up your Downloads folder and think….. wow…. so many files, such a big mess.

I found a python script written by Abdur Rahman and I optimised it a bit.

Here’s a script that organizes everything neatly:

"""
Auto-Organize Downloads Folder (Optimized)
Author: Abdur Rahman (https://medium.com/@abdur-rahman)
Code found on: https://blog.stackademic.com/
Optimized by: Theo van der Sluijs / https://itheo.tech 

This script organizes files in a specified folder (e.g., Downloads) into categorized subfolders
based on file types (Images, Videos, Documents, Archives, etc.). It moves each file into a designated 
folder according to its extension.

- Accepts folder path input from the user.
- Includes error handling for invalid or inaccessible folders.
- Creates subfolders as needed, and provides a summary message upon completion.
"""

import os
import shutil

def organize_folder(folder):
    """
    Organizes files in a specified folder by moving them into subfolders based on file type.

    Args:
        folder (str): The path to the folder to organize.

    Returns:
        None
    """
    # Define file type categories and their extensions
    file_types = {
        'Images': ['.jpeg', '.jpg', '.png', '.gif'],
        'Videos': ['.mp4', '.avi', '.mov'],
        'Documents': ['.pdf', '.docx', '.txt'],
        'Archives': ['.zip', '.rar']
    }

    # Counter for moved files
    moved_files_count = 0

    try:
        for filename in os.listdir(folder):
            file_path = os.path.join(folder, filename)

            # Only process files (skip directories)
            if os.path.isfile(file_path):
                ext = os.path.splitext(filename)[1].lower()

                # Find the category for the file extension
                for folder_name, extensions in file_types.items():
                    if ext in extensions:
                        target_folder = os.path.join(folder, folder_name)
                        os.makedirs(target_folder, exist_ok=True)

                        # Move file and print action
                        shutil.move(file_path, os.path.join(target_folder, filename))
                        print(f'Moved {filename} to {folder_name}')
                        moved_files_count += 1
                        break

    except Exception as e:
        print(f"Error: {e}")

    print(f"\nScript completed. {moved_files_count} files were organized.\n")

# Prompt user for folder path input with validation
while True:
    folder_path = input("Please enter the folder path to organize: ").strip()
    if os.path.isdir(folder_path):
        break
    print("Invalid folder path. Please enter a valid folder path.")

# Run the organizer
organize_folder(folder_path)

print("Folder organization is complete.")

Did you find this article valuable?

Support itheo.tech, I automate Sh!t by becoming a sponsor. Any amount is appreciated!