KITFORMA · EDITORIAL ANSWER
How do I avoid leaving a partially written JSON configuration file?
KitForma editorial guide. Write JSON to a temporary sibling, close it, and replace the destination only after serialization succeeds.
Step-by-step answer
import json
import os
import tempfile
from pathlib import Path
def save_json(path, value, fail_before_replace=False):
pending = None
try:
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8",
dir=path.parent, delete=False) as handle:
pending = Path(handle.name)
json.dump(value, handle, allow_nan=False)
handle.flush()
os.fsync(handle.fileno())
if fail_before_replace:
raise RuntimeError("Injected failure")
os.replace(pending, path)
finally:
if pending is not None:
pending.unlink(missing_ok=True)
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "config.json"
path.write_text('{"version":1}', encoding="utf-8")
try:
save_json(path, {"version": 2}, fail_before_replace=True)
except RuntimeError:
pass
print(json.loads(path.read_text(encoding="utf-8"))["version"])
save_json(path, {"version": 2})
print(json.loads(path.read_text(encoding="utf-8"))["version"])1
2Sources and verification
Sources checked:
This editorial answer was prepared by KitForma with AI assistance. It is not presented as a real member question or an independent user review. Check the sources and the result with your own file; report corrections in the discussion.