配置文件默认为conf.json
使用函数set完成追回配置项。
使用load或取配置项。
代码如下:
#!/usr/bin/env python3# -*- coding: utf-8 -*-‘‘‘json配置文件类,调用方法data_dict = {"a":"1", "b":"2"}JsonConf.set(data_dict)即可在当前目录下生成json文件:config.json‘‘‘import json
import osclass JsonConf:
‘‘‘json配置文件类‘‘‘@staticmethoddef store(data):with open("config.json", ‘w‘) as json_file:json_file.write(json.dumps(data, indent=4))@staticmethoddef load():if not os.path.exists(‘config.json‘):with open("config.json", ‘w‘) as json_file:passwith open(‘config.json‘) as json_file:
try:data = json.load(json_file)except:data = {}
return data@staticmethoddef set(data_dict):
json_obj = JsonConf.load()
for key in data_dict:json_obj[key] = data_dict[key]JsonConf.store(json_obj)print(json.dumps(json_obj, indent=4))if __name__=="__main__":data = {"a":" 1", "f":"100","b":"3000"}JsonConf.set(data)
原文:http://www.cnblogs.com/luhouxiang/p/7450899.html