Move it. Copy it. Retire it..
Manage a file lifecycle inside an explicitly owned practice directory.
01 The idea
File lifecycle operations should make their scope obvious. Copying preserves an original; renaming changes its location; unlink removes a file directory entry. These operations are not automatically reversible. A small program can use a temporary directory as an owned sandbox for a practice workflow, then leave cleanup to its context manager.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
from pathlib import Path
from tempfile import TemporaryDirectory
import shutil
with TemporaryDirectory() as folder:
root = Path(folder)
source = root / "draft.txt"
source.write_text("Orbit brief", encoding="utf-8")
copy = root / "backup.txt"
shutil.copy2(source, copy)
renamed = source.rename(root / "final.txt")
print(sorted(path.name for path in root.iterdir()))
renamed.unlink()
print(copy.read_text(encoding="utf-8"))['backup.txt', 'final.txt'] Orbit brief
03 Under the hood
- 1
TemporaryDirectory owns only its generated directory. Everything in this example is created beneath that directory, so the cleanup scope is explicit.
- 2
copy2 attempts to preserve metadata as well as contents, but cannot promise to copy every platform-specific attribute. Decide which metadata matters to your application.
- 3
rename and replace have different overwrite expectations across platforms. Use an explicit policy and handle errors rather than assuming a destination can always be overwritten.
04 Your turn, builder
Create a practice file, rename it, then verify the old path no longer exists.
Reveal one possible solution +
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
source = Path(folder) / "before.txt"
source.write_text("draft", encoding="utf-8")
destination = source.rename(Path(folder) / "after.txt")
print(source.exists(), destination.exists())05 Check your signal
What does unlink remove in this example?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.