
You have 300 scanned files named scan0001.pdf… and an Excel sheet saying what each should be called. Here is a safe script to rename them all.
The Excel list
rename.xlsx with two columns: Old (current file name) and New (wanted name, e.g. INV-2026-0412 Acme Traders.pdf).
Advertisement
The script
from pathlib import Path
import pandas as pd
FOLDER = Path(r"C:\Scans\April")
DRY_RUN = True # first run: only show what would happen
df = pd.read_excel("rename.xlsx", dtype=str)
bad = "<>:\"/\|?*"
log = []
for old, new in zip(df["Old"].str.strip(), df["New"].str.strip()):
src, dst = FOLDER / old, FOLDER / "".join(c for c in new if c not in bad)
if not src.exists():
log.append((old, new, "MISSING")); continue
if dst.exists():
log.append((old, new, "TARGET EXISTS")); continue
if not DRY_RUN:
src.rename(dst)
log.append((old, dst.name, "would rename" if DRY_RUN else "renamed"))
pd.DataFrame(log, columns=["Old", "New", "Result"]).to_excel("rename-log.xlsx", index=False)
print(pd.DataFrame(log)[2].value_counts())
How to use it safely
- Run with
DRY_RUN = Trueand openrename-log.xlsx. - Fix anything marked MISSING or TARGET EXISTS in your sheet.
- Copy the folder as a backup, set
DRY_RUN = Falseand run again.
Why each check matters
- Invalid characters (
/ : ?etc.) are removed because Windows won’t allow them in names. - Target exists stops two rows overwriting each other.
- The log is your proof of what changed — keep it with the files.
New to Python? Start with our Python beginner course.
✨ Ask AI about this article
Stuck on a step? Ask a question and the AI answers using this article.
Free · AI can be wrong