File Organizer Project (Code) in Python

← Back to Projects

File Organizer in Python.

About the project: This is Python project that helps you organize files in a specified directory by moving them into subfolders based on their file type.

The program will scan a directory for files, determine their extensions (e.g., .jpg, .pdf, .mp3), and then create subdirectories for each file type.

Finally, it will move the files into their corresponding folders, making your directory much neater.


How to use this program:

This Python script is a complete and interactive tool.

When you run it, you'll be prompted to enter the path of a directory.

The program will then automatically create subfolders and move the files into them based on the file extensions defined in the script.

You can easily customize the extension_to_folder dictionary to add or change the categories.


Project Level: Intermediate

You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.

Steps: Follow these steps

Step 1: Copy below code using green 'copy' button.

Step 2: Paste the code on your chosen editor.

Step 3: Save the code with filename and .py extention.

Step 4: Run (Press F5 if using python IDLE)




# file_organizer.py

import os
import shutil
import sys

def organize_files(directory_path):
    """
    Organizes files in a given directory by moving them into subfolders
    based on their file extension.

    Args:
        directory_path (str): The path to the directory to be organized.
    """
    if not os.path.isdir(directory_path):
        print(f"Error: The path '{directory_path}' is not a valid directory.")
        return

    print(f"\nScanning directory: {directory_path}")
    files = os.listdir(directory_path)
    
    # Dictionary to map file extensions to directory names
    # You can customize this as needed
    extension_to_folder = {
        # Images
        '.jpg': 'Images', '.jpeg': 'Images', '.png': 'Images', '.gif': 'Images',
        '.bmp': 'Images', '.svg': 'Images',
        # Documents
        '.pdf': 'Documents', '.docx': 'Documents', '.doc': 'Documents', '.txt': 'Documents',
        '.pptx': 'Documents', '.xlsx': 'Documents', '.xls': 'Documents',
        # Audio
        '.mp3': 'Audio', '.wav': 'Audio', '.aac': 'Audio', '.flac': 'Audio',
        # Video
        '.mp4': 'Videos', '.mov': 'Videos', '.avi': 'Videos', '.mkv': 'Videos',
        # Executables and archives
        '.exe': 'Applications', '.zip': 'Archives', '.rar': 'Archives',
        # Scripts
        '.py': 'Scripts', '.js': 'Scripts', '.html': 'Scripts', '.css': 'Scripts',
    }

    organized_count = 0
    for filename in files:
        # Skip directories and the script itself
        if os.path.isdir(os.path.join(directory_path, filename)):
            continue
        
        # Get the file extension
        _, file_extension = os.path.splitext(filename)
        
        if file_extension.lower() in extension_to_folder:
            folder_name = extension_to_folder[file_extension.lower()]
            folder_path = os.path.join(directory_path, folder_name)
            
            # Create the subfolder if it doesn't exist
            if not os.path.exists(folder_path):
                os.makedirs(folder_path)
                print(f"Created directory: {folder_path}")
            
            # Move the file
            old_path = os.path.join(directory_path, filename)
            new_path = os.path.join(folder_path, filename)
            
            try:
                shutil.move(old_path, new_path)
                print(f"Moved: '{filename}' -> '{folder_name}/'")
                organized_count += 1
            except Exception as e:
                print(f"Error moving file '{filename}': {e}")
        else:
            print(f"Skipped: '{filename}' (unknown file type)")

    print(f"\nOrganization complete! Moved {organized_count} files.")

def main():
    """
    Main function to run the File Organizer.
    """
    print("--- Python File Organizer ---")
    
    # Get the directory from the user
    directory_to_organize = input("Enter the path to the directory to organize: ").strip()
    
    if not directory_to_organize:
        print("Directory path cannot be empty.")
        sys.exit(1)
    
    organize_files(directory_to_organize)

# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
    main()