码迷,mamicode.com
首页 > 编程语言 > 详细

python写的读取json配置文件

时间:2017-08-30 01:03:10      阅读:379      评论:0      收藏:0      [点我收藏+]

标签:sts   store   exist   ati   import   path   dict   mono   exists   

配置文件默认为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)

python写的读取json配置文件

标签:sts   store   exist   ati   import   path   dict   mono   exists   

原文地址:http://www.cnblogs.com/luhouxiang/p/7450899.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!