How do you write a config file atomically?
AdvancedConceptExceptions, context managers, files & logging
Answer
Write to a temp file in the same directory, flush and fsync, then os.replace() it over the target. os.replace is atomic on POSIX when source and destination are on the same filesystem, so readers see either the old file or the new one, never a half-written file.
import os, tempfile
def atomic_write(path, data):
d = os.path.dirname(os.path.abspath(path))
with tempfile.NamedTemporaryFile("w", dir=d, delete=False, encoding="utf-8") as tmp:
tmp.write(data)
tmp.flush()
os.fsync(tmp.fileno())
os.replace(tmp.name, path)
This is how we update nginx upstream files or kubeconfigs that other processes read.
More on Exceptions, context managers, files & logging
How does `try` / `except` / `else` / `finally` work?BeginnerWhy is a bare `except:` (or `except Exception: pass`) dangerous?BeginnerWhat is exception chaining, and what is `raise ... from`?IntermediateWhen should you define custom exception classes?IntermediateWhat is the EAFP vs LBYL style, and which does Python prefer?IntermediateHow does a `with` statement work, and why use it for files?Beginner