"""Timestamped archives plus atomic working files. No hardware access.""" from datetime import datetime from zoneinfo import ZoneInfo from pathlib import Path import json,uuid,os def stamp(): return datetime.now(ZoneInfo('Asia/Shanghai')).strftime('%Y%m%d_%H%M%S_%f') def save_json(path,data): path=Path(path);path.parent.mkdir(parents=True,exist_ok=True) if path.exists(): archive=path.parent/'history';archive.mkdir(exist_ok=True) archived=archive/f'{path.stem}_{stamp()}_{uuid.uuid4().hex[:6]}{path.suffix}' with archived.open('xb') as f:f.write(path.read_bytes()) temp=path.with_name(path.name+'.'+uuid.uuid4().hex+'.tmp') with temp.open('x') as f: json.dump(data,f,indent=2,ensure_ascii=False);f.flush();os.fsync(f.fileno()) temp.replace(path)