Linked Questions

Popular Questions

I have an excel file with a column named old_name. Which is a column of a list of old filenames that need to be changed. Then in the next column I have new_name. I want to change all pdfs in a directory from old name to the new name. Like this:

Old_name New_name
Nike Adidas
Puma Gucci

The code I've tried is:

import os
import pandas as pd

directory = r"C:\x\x\x\PDF"
df = pd.read_excel("New_name.xlsx")

for index, row in df.iterrows():
    old_name = row["Old_name"]
    new_name = row["New_name"]
    old_path = os.path.join(directory, old_name)
    new_path = os.path.join(directory, new_name)

    if os.path.exists(old_path) and old_name.endswith(".pdf"):
        os.rename(old_path, new_path)
        print(f"Renamed {old_path} to {new_path}")

The problem is that I get a error of FileNotFoundError. Using this code, it seems like it's looking for the new_name data in the directory, they are not there (they are in the excel) so then it says error due to not finding in the directory.

Related Questions