Skip to main content

Command Palette

Search for a command to run...

How to Automate Renaming Files in a Folder with Python

Updated
3 min read
How to Automate Renaming Files in a Folder with Python
M

Essentialist Programmer, Minimalist, Machine Learning Enthusiast.

Imagine you have a folder full of files with random names, and you need to rename them in a specific format. Manually renaming each file could take forever. Luckily, Python can help automate this!

Everyone wants automation right!!

Now let’s introduce the concept…

Renaming files manually can be a tedious task, especially when you’re dealing with hundreds of files. But with Python, you can automate this process efficiently! In this blog post, we’ll look at how to write a Python script that renames files in a folder using the os module.

Solution Overview:

We’ll use the os module to interact with the file system. This module allows us to list files in a folder, check if they are files (and not directories), and rename them according to a custom naming scheme.

Pre-requisite:

To run the code you need some important tools on your system:

  • Python 3. x

  • pip3 (Python Package Manager)

  • A Code Editor (VS Code, or any of your code, but I will be using VS Code)

  • Basic Knowledge of Python

You can verify Python is installed correctly by typing:

$ python3

Step-by-Step Guide:

import os

def rename_files_in_folder(folder_path: str, prefix="file"):
    """
    Automating Renaming Files in a Folder

    Args:
        folder_path (str): Path to the folder containing the files to be renamed
        prefix (str, optional): Prefix to the renamed files. Defaults to "file".
    """
    try:
        # List all the files in the folder
        files_list = os.listdir(folder_path)

        # Filter directories and get only files using List comprehension
        files = [f for f in files_list if os.path.isfile(os.path.join(folder_path, f))]

        # Rename the Files
        for index, filename in enumerate(files, start=1):
            # Get file extension
            file_extension = os.path.splitext(filename)[1]

            # Create new file name
            new_name = f"{prefix}_{index}{file_extension}"

            # Renaming File
            old_file_path = os.path.join(folder_path, filename)
            new_file_path = os.path.join(folder_path, new_name)

            os.rename(old_file_path, new_file_path)
            print(f"Renamed: {filename} -> {new_name}")

        print("Renaming Completed Successfully!")

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

# Run the Program
if __name__ == "__main__":
    folder_path = input("Enter the folder path: ").strip()
    prefix = input("Enter the file prefix (default is 'file'): ").strip() or "file"
    rename_files_in_folder(folder_path=folder_path, prefix=prefix)

Code Explanation:

  1. Listing Files: We use os.listdir() to get all files in the specified folder.

  2. Filtering Files: We filter out directories using os.path.isfile().

  3. Renaming: For each file, we generate a new name with a number suffix and preserve the original extension.

  4. Error Handling: We wrap everything in a try-except block to handle any potential issues, like invalid folder paths.

Use Cases:

• Organizing project files where each document should follow a naming pattern.

• Renaming photo files from a camera in a systematic way.

With just a few lines of Python code, you can automate the renaming of files in any folder. This can save time and eliminate manual errors. Feel free to customize this script to suit your needs!

Try out the script and let me know how it works for you! If you have any suggestions for improvements or new challenges you’d like me to tackle, drop a comment below.

Quick Python Hacks

Part 1 of 1

In this series, I’ll guide you through step-by-step examples, from automating simple tasks like retrieving saved WiFi passwords to creating QR codes. Expect fun and useful code snippets that you can try out right away to enhance your Python toolkit.