I have a CSV file which has two columns:
Filename_Old | Filename_New
Jean1_Aspect_Six.jpg | Jean1_Aspect_Six_New.jpg
Jean2_Aspect_Five.jpg | Jean2_Aspect_Ratio_TN.jpg
Jean1_Table_P2.jpg | Jean1_Table_TN.jpg
Jas_Snail_P3.png | Jas_P3_TN.png
I have more than a thousand pictures which I need to rename using this method. Can this be done using python? Thanks a lot.
You can use zip
to iterate over pairs of corresponding items:
import os
for old, new in zip(df['Filename_Old'], df['Filename_New']):
os.rename(old, new)
As you are batch processing a large number of files, it might also be worth doing a try
so that if one of the renames fails (e.g. one of the files was already renamed), it doesn't stop the whole operation. For example:
for old, new in zip(df['Filename_Old'], df['Filename_New']):
try:
os.rename(old, new)
except OSError as exc:
print(f'WARNING: could not rename {old} to {new}: {exc}')
else:
print(f'renamed {old} to {new}')
Note that I am taking your question to mean the raw contents of your CSV file looks like:
Filename_Old,Filename_New
Jean1_Aspect_Six.jpg,Jean1_Aspect_Six_New.jpg
Jean2_Aspect_Five.jpg,Jean2_Aspect_Ratio_TN.jpg
Jean1_Table_P2.jpg,Jean1_Table_TN.jpg
Jas_Snail_P3.png,Jas_P3_TN.png
and that you have read it in using:
import pandas as pd
df = pd.read_csv("your_file.csv")