Files
iOSAI/Utils/IOSAIStorage.py

89 lines
2.7 KiB
Python
Raw Permalink Normal View History

2025-09-20 21:57:37 +08:00
import json
2025-09-28 20:42:01 +08:00
import os
2025-09-20 21:57:37 +08:00
from pathlib import Path
class IOSAIStorage:
@staticmethod
def _get_iosai_dir() -> Path:
"""获取 C:/Users/<用户名>/IOSAI/ 目录"""
user_dir = Path.home()
iosai_dir = user_dir / "IOSAI"
iosai_dir.mkdir(parents=True, exist_ok=True)
return iosai_dir
2025-09-28 20:42:01 +08:00
2025-09-20 21:57:37 +08:00
@classmethod
2025-09-28 20:42:01 +08:00
def save(cls, data: dict | list, filename: str = "data.json", mode: str = "overwrite") -> Path:
2025-09-20 21:57:37 +08:00
file_path = cls._get_iosai_dir() / filename
2025-09-28 20:42:01 +08:00
file_path.parent.mkdir(parents=True, exist_ok=True)
def _load_json():
try:
return json.loads(file_path.read_text("utf-8"))
except Exception:
return {} if isinstance(data, dict) else []
if mode == "merge" and isinstance(data, dict):
old = _load_json()
if not isinstance(old, dict):
old = {}
old.update(data)
to_write = old
elif mode == "append" and isinstance(data, list):
old = _load_json()
if not isinstance(old, list):
old = []
old.extend(data)
to_write = old
else:
to_write = data # 覆盖
# 原子写入
tmp = file_path.with_suffix(file_path.suffix + ".tmp")
with open(tmp, "w", encoding="utf-8") as f:
json.dump(to_write, f, ensure_ascii=False, indent=2)
os.replace(tmp, file_path)
print(f"[IOSAIStorage] 已写入: {file_path}")
2025-09-20 21:57:37 +08:00
return file_path
@classmethod
def load(cls, filename: str = "data.json") -> dict | list | None:
"""
C:/Users/<用户名>/IOSAI/filename 读取数据
"""
file_path = cls._get_iosai_dir() / filename
if not file_path.exists():
print(f"[IOSAIStorage] 文件不存在: {file_path}")
return {}
try:
with open(file_path, "r", encoding="utf-8") as f:
return json.load(f)
except Exception as e:
print(f"[IOSAIStorage] 读取失败: {e}")
return {}
@classmethod
def overwrite(cls, data: dict | list, filename: str = "data.json") -> Path:
"""
强制覆盖写入数据到 C:/Users/<用户名>/IOSAI/filename
无论是否存在都会写入
"""
file_path = cls._get_iosai_dir() / filename
try:
# "w" 模式本身就是覆盖,但这里单独做一个方法
with open(file_path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
print(f"[IOSAIStorage] 已覆盖写入: {file_path}")
except Exception as e:
print(f"[IOSAIStorage] 覆盖失败: {e}")
return file_path