DEV Community

Abhilash Panicker
Abhilash Panicker

Posted on

Renaming Folders in a Python Project with a Simple Script

Introduction:

Managing folder names in a project can sometimes become tedious, especially when you want to change the naming convention. In this tutorial, we'll show you how to create a Python script to rename folders in your project quickly and efficiently.

In our example, we will rename folders with the pattern "01_Lesson_Introduction" to "01_Introduction". We'll use the os and re libraries in Python to accomplish this task.

Creating the Python Script:

Start by importing the required libraries:

import os
import re
Enter fullscreen mode Exit fullscreen mode

Now, define a function called rename_folders that takes one argument, path, which is the path to the directory containing the folders you want to rename.

def rename_folders(path):
Enter fullscreen mode Exit fullscreen mode

Inside the function, create a list of directories in the provided path using a list comprehension.

    dir_list = [d for d in os.listdir(path) if os.path.isdir(os.path.join(path, d))]
Enter fullscreen mode Exit fullscreen mode

Next, start a loop that iterates through each folder in the dir_list:

    for folder in dir_list:
Enter fullscreen mode Exit fullscreen mode

In the loop, try to match the folder name to a given regular expression pattern:

        match = re.match(r"(\d{2})_Lesson_(.+)", folder)
Enter fullscreen mode Exit fullscreen mode

If there's a match, create a new folder name using the matched groups:

        if match:
            new_folder_name = f"{match.group(1)}_{match.group(2)}"
Enter fullscreen mode Exit fullscreen mode

Then, construct the full paths for the current folder and the new folder name:

            src = os.path.join(path, folder)
            dst = os.path.join(path, new_folder_name)
Enter fullscreen mode Exit fullscreen mode

Rename the folder using the os.rename function and print the renamed folder's source and destination paths for confirmation:

            os.rename(src, dst)
            print(f"Renamed folder '{src}' to '{dst}'")
Enter fullscreen mode Exit fullscreen mode

Finally, provide the path to your project folder and call the rename_folders function:

project_path = "/path/to/your/project"
rename_folders(project_path)
Enter fullscreen mode Exit fullscreen mode

Remember to replace "/path/to/your/project" with the actual path to your project folder.

Conclusion:

In this tutorial, we demonstrated how to create a Python script to rename folders in a project using the os and re libraries. This script can save you time when managing folder names and help keep your project organized.

Always remember to backup your project folder before running any scripts that modify its contents, just in case something goes wrong.

Top comments (0)