
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:
- Plan: work out every change and store it in a dict,
{old_name: new_name}. Touch nothing yet. - 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
- 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". - Complete
plan_renames(folder). Return a dict{old: new}for every file directly insidefolderwhose clean name is different. Skip names that are already clean. Skip folders, and don't look inside them. - Don't rename anything! This lesson only plans.
- 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". - Complete
plan_renames(folder). Return a dict{old: new}for every file directly insidefolderwhose clean name is different. Skip names that are already clean. Skip folders, and don't look inside them. - Don't rename anything! This lesson only plans.
main.py Python sleeping
Press Run to try your code, then Check to test it.