top of page

Organizing Files with Python

Organizing Files

Managing files manually can be tedious, especially when dealing with cluttered directories. Over time, our computers accumulate a variety of files of different types, leading to disorganization and difficulty in finding specific documents. Sorting these files manually is time-consuming and inefficient. In this post, I will show you how to build a Python script that automatically organizes files based on their file types into their respective folders. This approach saves time, keeps directories clean, and enhances productivity.


How It Works

We will categorize files by their extensions and move them into corresponding folders. First, the user provides a target directory, chooses whether to include files in subdirectories, and confirms the sorting operation. Then, the program starts the sorting.


Benefits of this Approach

By automating file organization, this approach minimizes human error and ensures consistency in file management. It also saves time, especially when dealing with larger directories, making it an efficient and scalable solution.


Step 1: Importing Dependencies

First, we start by importing the dependencies for our project.

import os
import shutil
import sys

Step 2: Getting User Input for Target Directory

We prompt the user to input the path for the target directory with disorganized filers and if the directory provided doesn’t exist, the program immediately exits.

target_dir = input("Provide Target Directory's FilePath: ")
def get_all_folders(directory):
    folder_paths = []
    for entry in os.scandir(directory):
        if entry.is_dir():
            folder_paths.append(entry.path)
    return folder_paths
if not os.path.exists(target_dir):
    print("Target directory does not exist!")
    sys.exit()

Step 3a: Choosing the Sorting Method

We ask the user whether they would like to sort all files including ones inside folders.

method = input("Would you like to sort included files stored in folders inside the target directory (y/n)?: ")

Step 3b: Sorting by Chosen Method

If the user decides to sort all files in the directory we iterate through all files and sort them. If the user decides to exclude subdirectories we iterate through all files excluding files in subdirectories and add them to a dictionary.

sorted_items = {}
if method.lower() in ["y", "yes"]:
    for root, dirs, files in os.walk(target_dir):
        for file in files:
            file_path = os.path.join(root, file)
            if os.path.isfile(file_path):
                ext = os.path.splitext(file)[-1].lower()
                if ext:
                    ext = ext[1:]  # Remove the leading dot
                    if ext in sorted_items:
                        sorted_items[ext].append(file_path)
                    else:
                        sorted_items[ext] = [file_path]
elif method.lower() in ["n", "no"]:
    sorted_items = {"folders": []}
    for item in os.listdir(target_dir):
        item_path = os.path.join(target_dir, item)
        if os.path.isdir(item_path):
            sorted_items["folders"].append(item_path)
        elif os.path.isfile(item_path):
            ext = os.path.splitext(item)[-1].lower()
            if ext:
                ext = ext[1:]  # Remove the leading dot
                if ext in sorted_items:
                    sorted_items[ext].append(item_path)
                else:
                    sorted_items[ext] = [item_path]

Step 4: Confirming the Sorting Operation

Before moving any files, the script asks the user for a final confirmation. If the user enters 'no,' the operation is canceled.


confirmation = input("Are you sure you would like to sort all files (y/n)?: ").lower()
if confirmation in ["y", "yes"]:
    pass
elif confirmation in ["n", "no"]:
    sys.exit("Operation cancelled.")
else:
    print("Invalid input.")
sys.exit()

Step 5: Moving Files to Respective Folders

Each file is moved into a corresponding folder named after its extension. If a folder does not exist for that extension, it is created.

for key, values in sorted_items.items():
    target_path = os.path.join(target_dir, key)
    os.makedirs(target_path, exist_ok=True)
    for file_path in values:
        try:
            shutil.move(file_path, target_path)
            print(f"Moved '{file_path}' to '{target_path}'.")
        except Exception as e:
            print(f"Failed to move '{file_path}' to '{target_path}': {e}")
if method.lower() in ["y", "yes"]:
    del_folders = input("Would you like to delete all folders that were left over, place them all in a new folder or do nothing (1, 2 or 3): ")
    if del_folders == "1":
        all_folders = get_all_folders(target_dir)
        for fold in all_folders:
            if fold.replace(target_dir, "").replace("/", "") not in sorted_items.keys():
                try:
                    shutil.rmtree(fold)
                    print(f"Folder '{fold}' successfully deleted.")
                except OSError as e:
                    print(f"Error: {fold} : {e.strerror}")
    elif del_folders == "2":
        os.makedirs(os.path.join(target_dir, "folders"),exist_ok = True)
        folders = os.path.join(target_dir, "folders")
        for item in get_all_folders(target_dir):
            if item.replace(target_dir, "").replace("/", "") not in sorted_items:
                shutil.move(item, folders)
    else:
        pass

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating

Subscribe

Subscribe to our mailing list for regular updates on news, events, insightful blogs, and free code!

Thanks for subscribing!

bottom of page