51 lines
1.3 KiB
Python
51 lines
1.3 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""原子文件写入(对齐安卓版 AtomicFiles 范式):
|
|
|
|
写 .tmp → flush+fsync → os.replace 原子替换 → 保留 .bak 上一份。
|
|
读取时若目标损坏则回退 .bak。
|
|
"""
|
|
import json
|
|
import os
|
|
import tempfile
|
|
|
|
|
|
def write_json(path, data):
|
|
os.makedirs(os.path.dirname(path) or '.', exist_ok=True)
|
|
bak = path + '.bak'
|
|
if os.path.exists(path):
|
|
try:
|
|
os.replace(path, bak)
|
|
except OSError:
|
|
pass
|
|
fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path) or '.',
|
|
suffix='.tmp')
|
|
try:
|
|
with os.fdopen(fd, 'w', encoding='utf-8') as f:
|
|
json.dump(data, f, ensure_ascii=False, indent=1)
|
|
f.flush()
|
|
os.fsync(f.fileno())
|
|
os.replace(tmp, path)
|
|
return True
|
|
except Exception:
|
|
try:
|
|
os.remove(tmp)
|
|
except OSError:
|
|
pass
|
|
# 回滚 .bak
|
|
if os.path.exists(bak) and not os.path.exists(path):
|
|
try:
|
|
os.replace(bak, path)
|
|
except OSError:
|
|
pass
|
|
return False
|
|
|
|
|
|
def read_json(path):
|
|
for p in (path, path + '.bak'):
|
|
try:
|
|
with open(p, 'r', encoding='utf-8') as f:
|
|
return json.load(f)
|
|
except Exception:
|
|
continue
|
|
return None
|