Python · File Reliability
Python File Updates: Prepare a Temporary File Before Replacing the Live One
Write a complete temporary file beside the destination, close it, then replace the live path with explicit cleanup.

An export job that writes directly over a live JSON file can leave readers with incomplete content if writing fails. Separate preparation from replacement.
Prepare beside the destination
Create a named temporary file in the destination directory with tempfile.NamedTemporaryFile(dir=target.parent, delete=False). Write the complete document, then close the file before attempting replacement. Using the destination directory avoids an accidental move between filesystems, which os.replace() may reject.
Replace after preparation succeeds
A compact outline is:
from pathlib import Path
from tempfile import NamedTemporaryFile
import os
target = Path("export.json")
pending = None
try:
with NamedTemporaryFile(mode="w", encoding="utf-8",
dir=target.parent, delete=False) as stream:
pending = Path(stream.name)
stream.write('{"ready": true}')
os.replace(pending, target)
finally:
if pending is not None:
pending.unlink(missing_ok=True)
The existing destination file is replaced when permissions allow. Python documents a successful rename as atomic, a POSIX requirement. Preparation failures occur before the replacement call, preserving the previous destination.
Define the remaining guarantees
Atomic replacement alone does not guarantee persistence after power loss or coordinate competing writers. Decide separately whether the application needs filesystem-specific durability measures or a writer lock. Also review destination permissions: the replacement uses the temporary file rather than preserving every property of the old file.
For a generated export, test a write failure before replacement and confirm readers can still open the previous complete document.