Traverse and Rename files in folder

I recently encountered a problem wherein I had to traverse through all the files in a folder and rename each file.

The original files is as shown below having a set of characters and number separated by an “-” (hyphen) with jpg extension.



d6445cef9361a2bf-3.jpg and so on.

Here, the requirement was to remove the left part of the “-” (hyphen) and retain only the number and the extension.

So, here is my approach.

from glob import glob
import os

pathFromUser = input("Enter the Path")
files_list = glob(os.path.join(pathFromUser, '*.jpg'))
for each_file in files_list:
    number = os.path.basename(each_file).split("-")[1].split(".")[0]
    os.rename(each_file, number + ".jpg")

In line 4, we ask the user to enter the path for the folder which contains all the files. In line 5, a list of all the files in the folder is assigned to the list called files_list. One should be aware that it’s not only the filename but a combination of both path and filename i.e., C:\foldername\d6445cef9361a2bf-1.jpg. In line 6, we loop through each file in the list. In line 7, the basename method is used to obtain the name of the file from the path and then we split the filename based on “-” (hyphen) and we again split the resultant value based on “.” (dot). This line results in a number present in the file and is assigned to the variable number. Then we use the method rename to rename each file to the value that is present in the number.

Leave a Reply

Your email address will not be published. Required fields are marked *