Replace Files without Truncating the Original First
Core idea
Prepare new content in a separate temporary file in the destination directory, close it, validate it, and replace the old name with os.replace. A successful replacement is atomic under POSIX semantics; same-filesystem placement avoids cross-device rename problems. Atomic visibility is not crash durability or concurrent-writer coordination.
from pathlib import Pathfrom tempfile import TemporaryDirectory
with TemporaryDirectory() as folder: root = Path(folder) import os p = root / "state.txt" p.write_text("old", encoding="utf-8") candidate = root / "candidate.txt" candidate.write_text("new", encoding="utf-8") if candidate.read_text(encoding="utf-8") == "new": os.replace(candidate, p) print(p.read_text(encoding="utf-8"), candidate.exists())The private root makes the fixed candidate name safe for this demonstration; production code should create a unique temp file.
Reject an invalid candidate
from pathlib import Pathfrom tempfile import TemporaryDirectory
with TemporaryDirectory() as folder: root = Path(folder) p = root / "state.txt" p.write_text("old", encoding="utf-8") candidate = root / "candidate.txt" candidate.write_text("", encoding="utf-8") if not candidate.read_text(encoding="utf-8"): candidate.unlink() print(p.read_text(encoding="utf-8"))Rejecting the candidate leaves the original intact.
Common mistake
Do not claim that rename preserves permissions or guarantees durability. A real update needs appropriate metadata, sync, locking and cleanup policies for the target platform.
Practice
Inside a private temporary directory, repeat the replacement with a valid and invalid candidate; check that a rejected update retains the old contents.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Replacement contracts
Check your understanding of safe file replacement.
What is printed?
from pathlib import Pathfrom tempfile import TemporaryDirectory
with TemporaryDirectory() as folder: root = Path(folder) import os a,b=root/"a",root/"b" a.write_text("new", encoding="utf-8") b.write_text("old", encoding="utf-8") os.replace(a,b) print(b.read_text(encoding="utf-8"))What is printed?
from pathlib import Pathfrom tempfile import TemporaryDirectory
with TemporaryDirectory() as folder: root = Path(folder) import os a,b=root/"a",root/"b" a.touch() os.replace(a,b) print(a.exists(), b.exists())When should validation occur in this workflow?
What is not guaranteed by atomic replacement alone?