Fork自 CSDN 技术社区 / CSDN-技能森林
import json import os import logging import sys logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) def load_json(p): with open(p, 'r', encoding="utf-8") as f: try: return json.loads(f.read()) except UnicodeDecodeError: logger.info( "json 文件 [{p}] 编码错误,请确保其内容保存为 utf-8 或 base64 后的 ascii 格式。") def dump_json(p, j, exist_ok=False, override=False): if os.path.exists(p): if exist_ok: if not override: return else: logger.error(f"{p} already exist") sys.exit(0) with open(p, 'w+', encoding="utf8") as f: f.write(json.dumps(j, indent=2, ensure_ascii=False))