Welcome folks today in this blog post we will be writing the python script
to automatically rename
all the files present inside the directory
with a custom pattern name
using the os
module. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an app.py
file and copy paste the following code
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import os # specify the directory path directory_path = "images" # specify the custom pattern for file names file_name_pattern = "file_" # get a list of all files in the directory files = os.listdir(directory_path) # loop through each file for index, file in enumerate(files): # get the absolute path of the file file_path = os.path.join(directory_path, file) # check if the file is a file (not a directory) if os.path.isfile(file_path): # get the file extension file_extension = os.path.splitext(file)[1] # construct the new file name using the custom pattern and file extension new_file_name = file_name_pattern + str(index) + file_extension # construct the absolute path of the new file name new_file_path = os.path.join(directory_path, new_file_name) # rename the file os.rename(file_path, new_file_path) |
As you can see in the above code you need to replace the path
of the directory where all the files
are present and then it will loop through all the files
with different extensions as well and it will rename the files with the provided
pattern in the above code. You can edit the pattern according to your choice. Now you need to create the images
folder and store the files as shown below