• python写的读取json配置文件


    配置文件默认为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 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)
  • 相关阅读:
    蛋糕多少钱?
    【FJOI2015】金币换位问题
    撞车
    【BZOJ 1097】旅游景点atr
    codeforces 434D
    codeforces 480D
    bzoj网络流
    bzoj2039
    bzoj1927
    bzoj1070
  • 原文地址:https://www.cnblogs.com/luhouxiang/p/7450899.html
Copyright © 2020-2023  润新知