Simplify Your File Organization with Python: A Step-by-Step Tutorial to Automatically Rename Files

Learn how to use a Python script to automate the renaming of files, making it easier to manage and organize your media collection.

Arap Tala's image

Moses Bartena

1 year ago

Simplify Your File Organization with Python: A Step-by-Step Tutorial to Automatically Rename Files's cover photo

Managing a large collection of media files can be a daunting task, especially when filenames are cluttered with unnecessary prefixes, suffixes, or inconsistent formatting. This tutorial will guide you through a Python script designed to automate the renaming of files, making your file organization process efficient and effortless.


Step 1: Import Necessary Modules

First, we need to import the necessary Python modules:


import os
import time
import re


  • os: Used for interacting with the operating system, such as listing files and renaming them.
  • time: Allows us to measure the execution time of our script.
  • re: Provides support for regular expressions, enabling complex string manipulations.


Step 2: Define the rename_files Function

Next, we'll define a function named rename_files that takes the path to the folder containing the files as an argument.


def rename_files(folder_path):
    start_time = time.time()  # Record the start time
    files = os.listdir(folder_path)  # List all files in the folder
    total_files = len(files)  # Get the total number of files
    processed_files = 0  # Counter for processed files


This function will list all the files in the specified folder and track the number of processed files.


Step 3: Specify Phrases to be Bracketed

We also define a list of phrases that we want to enclose in brackets:


    phrases = [
        "Official Video",
        "Official Music Video",
        "Official Lyric Video",
        "Official Audio",
        "Audio",
        "Visualizer",
        "Music Visualizer"
    ]


These phrases are commonly found in media file names and are helpful when bracketed for better readability.


Step 4: Process and Rename Each File

Now, let's process each file in the folder:


    for file_name in files:
        new_name = file_name

        # Remove "y2mate.com - " prefix
        if new_name.startswith("y2mate.com - "):
            new_name = new_name[len("y2mate.com - "):]

        # Remove "_1080p" suffix
        if "_1080p" in new_name:
            base, ext = os.path.splitext(new_name)
            if base.endswith("_1080p"):
                base = base[:-len("_1080p")]
                new_name = base + ext

        # Replace double spaces with a hyphen
        new_name = new_name.replace("  ", " - ")

        # Bracket specified phrases
        for phrase in phrases:
            new_name = re.sub(rf'\b{phrase}\b', rf'({phrase})', new_name)

        # Rename the file if changes were made
        if new_name != file_name:
            old_path = os.path.join(folder_path, file_name)
            new_path = os.path.join(folder_path, new_name)
            os.rename(old_path, new_path)
            processed_files += 1

            # Calculate and print progress percentage
            progress_percent = (processed_files / total_files) * 100
            print(f'Renaming file: {processed_files} -> ({progress_percent:.2f}% complete)')


Here’s what each section does:


Remove Prefixes/Suffixes: The script first removes the "y2mate.com - " prefix and "_1080p" suffix from the file names.

Replace Double Spaces: Any double spaces in the filenames are replaced with hyphens.

Bracket Important Phrases: The phrases specified in the phrases list are enclosed in brackets.

Rename the File: If any changes were made to the filename, the file is renamed accordingly, and the progress is printed.


Step 5: Measure and Display Execution Time

Finally, let's calculate how long it took to process all the files:


end_time = time.time()  # Record the end time
elapsed_time = end_time - start_time  # Calculate elapsed time
print(f'\nRenaming completed in {elapsed_time:.2f} seconds.')


This code snippet records the end time, calculates the elapsed time, and prints it out, giving you an idea of the script's performance.


Step 6: Run the Script

To run the script, specify the path to the folder containing the files you want to rename:


# Specify the path to the folder containing the files
folder_path = "target"
# Call the function to rename files in the specified folder
rename_files(folder_path)


Replace "target" with the actual path to your folder, and execute the script using a Python interpreter.


View the source code here on Github


  • #PythonProgramming #FileRenaming #PythonAutomation #MediaOrganization #BatchProcessing #PythonScript #FileManagement #FourPixelsStudioBlogs