Code

Plan the New Names

Pip wants tidy file names: lowercase, with dashes instead of spaces. "Storm Report.TXT" should become "storm-report.txt".

Renaming is hard to undo. So a careful tool works in two steps:

  1. Plan: work out every change and store it in a dict, {old_name: new_name}. Touch nothing yet.
  2. Apply: make the changes, only after the plan looks right.

Showing the plan without doing it is called a dry run or a preview.

plan = {"Storm Report.TXT": "storm-report.txt"}
for old, new in plan.items():
    print(f"{old} -> {new}")

A handy trick

name.split() with no argument splits on any run of spaces (or tabs) and drops spaces at the ends:

"  Storm   Report.TXT ".split()   # ['Storm', 'Report.TXT']
"-".join(["storm", "report.txt"]) # 'storm-report.txt'

Assignment

  1. Complete clean_name(name). Return the name in lowercase, with each run of spaces replaced by one -, and no spaces at the ends. " Old Map 2.PNG" becomes "old-map-2.png".
  2. Complete plan_renames(folder). Return a dict {old: new} for every file directly inside folder whose clean name is different. Skip names that are already clean. Skip folders, and don't look inside them.
  3. Don't rename anything! This lesson only plans.