python寫的讀取json配置文件

配置文件默認爲conf.jsonpython

使用函數set完成追回配置項。json

使用load或取配置項。函數

代碼以下:spa

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
json配置文件類,調用方法
data_dict = {"a":"1", "b":"2"}
JsonConf.set(data_dict)
便可在當前目錄下生成json文件:config.json
'''
import json 
import os
class JsonConf:
    '''json配置文件類'''
    @staticmethod
    def store(data):
        with open("config.json", 'w') as json_file:
            json_file.write(json.dumps(data, indent=4))
    @staticmethod  
    def load():
        if not os.path.exists('config.json'):
            with open("config.json", 'w') as json_file:
                pass       
        with open('config.json') as json_file:
            try:
                data = json.load(json_file)
            except:
                data = {}
            return data
        
    @staticmethod
    def 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)
相關文章
相關標籤/搜索