Iterating through file names in a folder and renaming with Python

Viewed 568

I have a folder containing 1000+ files. They all have a different name format (from very inconsistent name formatting over time), so I can't just use replace or split in Python. But I do have an Excel sheet with 2 columns

ShortName     FullName
Banana 2020   Banana_2020_Fruit.pdf
Apple 900     Apple_900_Fruit_v2.pdf
Pear 1800     Pear 1800_new.pdf
Plum 210      Plum210.pdf

How can I just rewrite all file names using the ShortName column?

import os
import pandas as pd

myfile = pd.read_excel("filetoexcel.xlsx")

for fileName in os.listdir("C:/Users/name/here/folder"):
   os.rename(fileName, fileName.replace(_____))
1 Answers

Does this work?

import pandas as pd
import os
from pathlib import Path as path

df = pd.read_excel(file)
df = df.set_index('ShortName')

folder = path('path/to/your/folder')
for file in folder.iterdir():
    shname = file.stem
    fname = df.loc[shname, 'FullName']
    os.rename(file, folder/path(fname))
Related