Files
creator/backend/fsutil.py
2026-06-30 00:14:18 +02:00

23 lines
654 B
Python

"""Atomic file writes: first a .tmp in the same directory, then os.replace.
A crash leaves at most a .tmp file behind — never a half-written target
file. The .tmp is overwritten on the next successful write.
"""
import json
import os
from pathlib import Path
def atomic_write_text(path: Path, text: str) -> None:
tmp = path.with_name(path.name + ".tmp")
with open(tmp, "w", encoding="utf-8") as f:
f.write(text)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, path)
def atomic_write_json(path: Path, obj, **dumps_kwargs) -> None:
atomic_write_text(path, json.dumps(obj, ensure_ascii=False, **dumps_kwargs))