json保存配置文件
Published on Aug. 22, 2023, 12:06 p.m.
json保存配置文件
import json
def save(data):
with open('config.json', 'w') as fw:
<h1>将字典转化为字符串</h1>
<h1>json_str = json.dumps(data)</h1>
<h1>fw.write(json_str)</h1>
<h1>上面两句等同于下面这句</h1>
json.dump(data,fw)
<h1>load json data from file</h1>
def load():
try:
with open('config.json','r') as f:
data = json.load(f)
return data
except:
with open('config.json', 'w') as fw:
json.dump({},fw)
return {}
CONF=load()