Python加载配置文件

l# 1. JSON

加载config.json文件为无序字典
base_path = sys.path[0]
config_path = os.path.join(base_path, 'devices/config/')


def get_ip(type_key):
    with open(config_path + 'config.json') as f:
        config = json.load(f)
    config_ip = config[type_key]['ip']
    config_port = config[type_key]['port']
    return config_ip, config_port
加载template.json为有序字典
base_path = sys.path[0]
config_path = os.path.join(base_path, 'devices/config/')

def get_template(file_name):
    with open(config_path + file_name) as f:
        template = json.load(f, object_pairs_hook=OrderedDict)
    return template

# 转成有序的str
config_str = json.dumps(OrderedDict(template))

2. ini

加载global.ini文件为无序字典
base_path = sys.path[0]
globalPath = os.path.join(base_path, 'etc/')
globalConfig = globalPath + '/global.ini'


def load_global_config():
    config_global = {}
    cf = ConfigParser.ConfigParser()
    cf.read(globalConfig)
    config_global['MariaDB'] = {'host_ip': str(cf.get("MariaDB", "host_ip")),
                                'port': str(cf.get("MariaDB", "port"))}

    return config_global

3. XML

转换xml文件为Element类
import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')    #载入数据
root = tree.getroot()    #获取根节点

#从字符串读取数据
root = ET.fromstring(country_data_as_string)

Python 标准库之 xml.etree.ElementTree

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值