DEV Community

Murabyte
Murabyte

Posted on

A safe batch rename in Python: preview first, then apply with an undo log

Disclosure: I make ScanNamer at Murabyte, which is mentioned at the end.

Batch renaming files is easy to get wrong: one bad rule and a folder of invoices turns into a mess. The safe way is a two-step flow: build a plan, show it, then apply it with an undo log. Here is a small Python version you can reuse for any rename job.

1. Build a plan, do not rename yet

from pathlib import Path
import re

BAD = re.compile(r'[\\/:*?"<>|]')

def safe(name: str, limit: int = 80) -> str:
    name = BAD.sub("-", name).strip(" .")
    return name[:limit] or "unnamed"

def make_plan(folder, namer):
    plan, taken = [], set()
    for p in sorted(Path(folder).glob("*.pdf")):
        new = safe(namer(p)) + p.suffix.lower()
        n, stem = 2, Path(new).stem
        while new.lower() in taken or (p.parent / new).exists() and p.parent / new != p:
            new = f"{stem}-{n}{p.suffix.lower()}"
            n += 1
        taken.add(new.lower())
        plan.append((p, p.parent / new))
    return plan
Enter fullscreen mode Exit fullscreen mode

Two rules matter: never overwrite an existing file, and make duplicate names unique (-2, -3) inside the same batch.

2. Show the preview

for old, new in plan:
    print(f"{old.name}  ->  {new.name}")
Enter fullscreen mode Exit fullscreen mode

Ask for a yes before going on. For files you cannot read confidently, leave them out of the plan and list them separately.

3. Apply with an undo log

import json
def apply(plan, log="rename_log.json"):
    done = []
    for old, new in plan:
        if old != new:
            old.rename(new)
            done.append([str(old), str(new)])
    Path(log).write_text(json.dumps(done, indent=2))

def undo(log="rename_log.json"):
    for old, new in reversed(json.loads(Path(log).read_text())):
        Path(new).rename(old)
Enter fullscreen mode Exit fullscreen mode

Undo runs in reverse order, so chained renames come back correctly.

4. Where the name comes from

For scanned invoices the namer function is the hard part: OCR the first page, then look for a date, a sender and a document type. That is where most of the errors come from, which is why the preview step is not optional.

If you want it ready-made

ScanNamer is a Windows app that does this flow for scanned invoices and receipts: OCR, date/sender/subject detection, a preview of new names, one-click apply and an undo for the whole batch, offline. Preview is free; renaming needs a license key. English OCR only for now, Windows only, one-time $12. It is a ready-made option if you would rather not set up Tesseract and maintain scripts. Disclosure again: my own product. Details: https://murabyte.gumroad.com/l/scannamer

python #automation #productivity #ocr

Written with AI assistance and reviewed by Murabyte.

Top comments (0)