Bulk File Renaming by Python
Have you ever faced a situation where you have a lot of files in a folder and you want to rename them all at once? For example, maybe you have a bunch of photos from your vacation and you want to rename them with the date and location. Or maybe you have some documents that need to be renamed with a specific format. How can you do this without manually renaming each file one by one?
One way to solve this problem is to use Python, a popular and powerful programming language. Python has a built-in module called os that allows you to interact with the operating system and perform various tasks such as creating, deleting, moving, and renaming files and folders. In this blog, I will show you how to use Python and the os module to bulk rename files in a folder.
Step 1: Import the os module
The first step is to import the os module in your Python script. You can do this by using the import statement at the top of your script. This will allow you to access the functions and variables of the os module in your code.
import os
Step 2: Get the list of files in the folder
The next step is to get the list of files in the folder that you want to rename. You can do this by using the os.listdir() function, which takes a path as an argument and returns a list of the names of the files and folders in that path. For example, if you have a folder called photos in your current working directory, you can get the list of files in that folder by using the following code:
files = os.listdir("photos")
This will assign a list of file names to the variable files. You can print this list to see what it contains:
print(files)
This might output something like this:
['IMG_001.jpg', 'IMG_002.jpg', 'IMG_003.jpg', ...]
Step 3: Loop through the list of files and rename them
The final step is to loop through the list of files and rename them according to your desired format. You can do this by using a for loop, which iterates over each element in a sequence and executes a block of code for each element. In this case, the sequence is the list of files and the block of code is the renaming operation.
To rename a file, you can use the os.rename() function, which takes two arguments: the old name and the new name of the file. For example, if you want to rename a file called IMG_001.jpg to 2023-11-22-Paris-001.jpg, you can use the following code:
os.rename("IMG_001.jpg", "2023-11-22-Paris-001.jpg")
This will rename the file in the same folder. If you want to move the file to a different folder, you can specify the full path of the new name. For example, if you want to move the file to a folder called renamed, you can use the following code:
os.rename("IMG_001.jpg", "renamed/2023-11-22-Paris-001.jpg")
This will create the folder renamed if it does not exist and move the file there.
Now, to rename all the files in the list, you can use a for loop and a string formatting method to generate the new names. For example, if you want to rename the files with the format YYYY-MM-DD-Location-NNN.jpg, where YYYY is the year, MM is the month, DD is the day, Location is the place, and NNN is a three-digit number, you can use the following code:
for i, file in enumerate(files):
# Get the file extension
ext = file.split(".")[-1]
# Generate the new name
new_name = f"2023-11-22-Paris-{i+1:03d}.{ext}"
# Rename the file
os.rename(file, new_name)
This will loop through the list of files and assign each file name to the variable file. The enumerate() function also returns the index of each file in the list, which is assigned to the variable i. This can be used to generate the three-digit number for the new name.
The split() method splits the file name by the dot character and returns a list of the parts. The [-1] index gets the last element of the list, which is the file extension. This is assigned to the variable ext.
The f prefix before the string indicates that it is a formatted string, which allows you to insert variables and expressions inside curly braces. The {i+1:03d} expression adds one to the index and formats it as a three-digit number with leading zeros. The {ext} expression inserts the file extension. The result is a new name with the desired format.
The os.rename() function renames the file with the old name and the new name. You can also specify a different folder for the new name if you want to move the file.
Complete Code:
import os
# define the directory path where the video files are located
directory_path = 'C:/Users/Admin/Video/'
# define a list of new sequential names
new_names = [
'File Name 1',
'File Name 2',
'File Name 3',
'File Name 4',
'File Name 5',
]
video_files = os.listdir(directory_path)
# extract the numeric part of the file name and sort the video files by their natural order
video_files.sort(key=lambda x: int(''.join(filter(str.isdigit, os.path.splitext(x)[0]))) if ''.join(filter(str.isdigit, os.path.splitext(x)[0])) else float('inf'))
# loop through the video files and rename them using the new sequential names
for i, file_name in enumerate(video_files):
file_path = os.path.join(directory_path, file_name)
new_file_name = os.path.join(directory_path, str(i+1) + ' - ' + new_names[i] + ' #shorts #java #indiantechnoera.mp4')
os.rename(file_path, new_file_name)
print(f"Renamed {file_name} to {new_names[i]}")
Conclusion
In this blog, I showed you how to use Python and the os module to bulk rename files in a folder. This can be useful for organizing your files and giving them meaningful names. You can modify the code to suit your needs and preferences. For example, you can change the format of the new name, the folder of the files, or the criteria for renaming. You can also use other modules and functions to get more information about the files, such as the date of creation, the size, the type, etc. I hope you found this blog helpful and learned something new. Thank you for reading!