Sunday, February 28, 2021

Rename multiple files with new names in excel spreadsheet

In the past, I have written similar script titled "Python script to rename multiple files/folders".

The only difference here is that the new file names will come from a column in excel spreadsheet instead of being generated within the script.

Here below is the spreadsheet file that contains the current file names and their corresponding new names.

For example image '4.jpg' would be renamed to 'Barack Obama.jpg', '9.jpg' to 'Donald Trump.jpg', '30.jpg' to 'Joseph Robinette Biden Jr.jpg'... and so on.

Note that all the images are of the same extension (.jpg), so we will maintain the extension.

The script

First, we will read the excel file using pandas (into a dataframe) and create a dictionary with the two columns where the keys are the 'old name' and the values are the 'new names'.

import os
import pandas as pd
import natsort

names_df = pd.read_excel(r"C:\Users\Yusuf_08039508010\Desktop\rename.xlsx")

names_df_dict = dict(zip(names_df['Old Name'], names_df['New Name']))

Now, we can access the values of the dictionary by their keys like so: names_df_dict['1.jpg']. With this, we will loop over the keys dynamically and rename the images accordingly.

images_folder = r'C:\Users\Yusuf_08039508010\Documents\US Presidents'

for file in os.listdir(images_folder):
    print ('Renaming...', names_df_dict[file])
    # Use os.path() to contruct absolute path to the images... 
    # ALternatively, we could change directory (os.chdir()) to the images folder
    old_img_name = os.path.join(images_folder, file)
    new_img_name = os.path.join(images_folder, names_df_dict[file] + '.jpg')
    os.rename(old_img_name, new_img_name)

To be sure our renaming script did a perfect job, lets verify the last three presidents that is:-

  • '4.jpg' would be renamed to 'Barack Obama.jpg', 
  • '9.jpg' to 'Donald Trump.jpg', 
  • '30.jpg' to 'Joseph Robinette Biden Jr.jpg'

That is it!

No comments:

Post a Comment