Files
Crypto_Scam/persistence.py
T

28 lines
879 B
Python

"""Atomic local JSON snapshots; callers must handle write failures explicitly."""
from __future__ import annotations
import json
import os
import tempfile
from pathlib import Path
def atomic_write_json(path: Path, payload) -> None:
"""Flush a new snapshot before replacing the old file, or leave the old file intact."""
path = Path(path)
encoded = json.dumps(payload, ensure_ascii=False, allow_nan=False).encode("utf-8")
path.parent.mkdir(parents=True, exist_ok=True)
fd, temporary = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=path.parent)
try:
with os.fdopen(fd, "wb") as stream:
stream.write(encoded)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
finally:
try:
os.unlink(temporary)
except FileNotFoundError:
pass