I have a CSV file which has two columns:
JavaScript
x
7
1
Filename_Old | Filename_New
2
3
Jean1_Aspect_Six.jpg | Jean1_Aspect_Six_New.jpg
4
Jean2_Aspect_Five.jpg | Jean2_Aspect_Ratio_TN.jpg
5
Jean1_Table_P2.jpg | Jean1_Table_TN.jpg
6
Jas_Snail_P3.png | Jas_P3_TN.png
7
I have more than a thousand pictures which I need to rename using this method. Can this be done using python? Thanks a lot.
Advertisement
Answer
You can use zip
to iterate over pairs of corresponding items:
JavaScript
1
5
1
import os
2
3
for old, new in zip(df['Filename_Old'], df['Filename_New']):
4
os.rename(old, new)
5
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:
JavaScript
1
8
1
for old, new in zip(df['Filename_Old'], df['Filename_New']):
2
try:
3
os.rename(old, new)
4
except OSError as exc:
5
print(f'WARNING: could not rename {old} to {new}: {exc}')
6
else:
7
print(f'renamed {old} to {new}')
8
Note that I am taking your question to mean the raw contents of your CSV file looks like:
JavaScript
1
6
1
Filename_Old,Filename_New
2
Jean1_Aspect_Six.jpg,Jean1_Aspect_Six_New.jpg
3
Jean2_Aspect_Five.jpg,Jean2_Aspect_Ratio_TN.jpg
4
Jean1_Table_P2.jpg,Jean1_Table_TN.jpg
5
Jas_Snail_P3.png,Jas_P3_TN.png
6
and that you have read it in using:
JavaScript
1
3
1
import pandas as pd
2
df = pd.read_csv("your_file.csv")
3