Atomic file write with temp file and rename
Python
import os
import tempfile
from pathlib import Path
def atomic_write(path: str | Path, text: str) -> None:
"""Replace a file atomically: write a temp file, sync it, then rename."""
target = Path(path)
target.parent.mkdir(parents=True, exist_ok=True)
fd, tmp_name = tempfile.mkstemp(dir=target.parent, prefix=f".{target.name}.")
try:
with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
handle.write(text)
handle.flush()
os.fsync(handle.fileno())
os.replace(tmp_name, target)
except BaseException:
try:
os.unlink(tmp_name)
except FileNotFoundError:
pass
raise
if __name__ == "__main__":
atomic_write("build/report.txt", "all good\n")