Python Path.rename
Move an existing draft to a new name in the same directory.
A simple example
Path.rename
- Start with A file named a.txt
- Do this Rename it to b.txt
- Result b.txt holds the original contents
Syntax
draft.rename(destination)
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyPublish a signed attendance sheet
A class representative edits a draft until the names have been checked. Once the sheet is signed, rename it in the same workspace and confirm the final name is available for publication.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
base = Path(folder)
draft = base / "draft.txt"
draft.write_text("signed", encoding="utf-8")
published = draft.rename(base / "attendance.txt")
if published.is_file() and not draft.exists():
print(published.name)
attendance.txt
After the successful rename the final entry identifies the published sheet.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. Rename the draft to its final name. What text can the next shift read under that name?
Prepare a studio handover
A stage manager saves a two-word instruction for the next shift. Rename the draft to its final name. What text can the next shift read under that name?
What to watch for
Moving across storage volumes can have different failure and atomicity guarantees.