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
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):
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))]
Next, start a loop that iterates through each folder in the dir_list:
for folder in dir_list:
In the loop, try to match the folder name to a given regular expression pattern:
match = re.match(r"(\d{2})_Lesson_(.+)", folder)
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)}"
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)
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}'")
Finally, provide the path to your project folder and call the rename_folders function:
project_path = "/path/to/your/project"
rename_folders(project_path)
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)