# 第29章示例:配置文件存取(json)

import json

# 1. 存配置
config = {
    "username": "皮皮",
    "theme": "dark",
    "volume": 80,
}

with open("config.json", "w", encoding="utf-8") as f:
    json.dump(config, f, ensure_ascii=False, indent=2)

# 2. 取配置(带异常兜底)
def load_config():
    try:
        with open("config.json", "r", encoding="utf-8") as f:
            return json.load(f)
    except FileNotFoundError:
        return {}      # 第一次运行,没有配置
    except json.JSONDecodeError:
        print("配置文件损坏,已重置")
        return {}

data = load_config()
print("用户名:", data.get("username"))
print("主题:", data.get("theme"))
print("音量:", data.get("volume"))
