每天努力一点点,坚持下去 ------ 博客首页

python解析配置文件ini、yaml

我们经常会用到ini、yaml等配置文件。使用的时候需要解析,学习一下怎么解析配置文件

1、解析ini文件

import configparser

c = configparser.ConfigParser() #实例化
c.read("test.ini")
print(c.sections()) #所有的节点
print(c["mysql"]) #获取某个节点
node_dict = dict(c["mysql"]) #可以转成字典
print(node_dict)

# 下面是封装的函数,以后可以直接使用
def get_config_form_ini(file_name, node):
    #filename 文件名
    #node 节点
    if not os.path.isfile(file_name): #判断文件是否存在,不存报错
        raise FileNotFoundError

    c = configparser.ConfigParser() #实例化解析类
    c.read(file_name) #读取文件
    if node in c.sections(): #判断节点是否存在
        return dict(c[node]) #返回内容

2、解析yaml文件

yaml是比较常见的一种配置文件,解析它需要安装pyyaml模块

pip install pyyaml

 方法一:

import yaml
import os

#下面是解析
with open("config.yaml", encoding="utf-8") as fr:
    result = yaml.load(fr, yaml.SafeLoader)
    print(result)

def get_config_form_yaml(file_name):
    if not os.path.isfile(file_name):  # 判断文件是否存在,不存报错
        raise FileNotFoundError

    with open(file_name, encoding="utf-8") as fr:
        return yaml.load(fr, yaml.SafeLoader)
    
 #把字典写到yaml文件里面

d = {'url': 'http://127.0.0.1:1111/login', 'method': 'get', 'headers': {'token': 'xxx'}, 'data': {'name': 'abc', 'password': 'xxx'}}

with open("config2.yaml",'w', encoding="utf-8") as fr:
    yaml.dump(d,fr)

 方法二:

tool.py

def loadYmlFile(yml_file):
    with open(yml_file, 'r', encoding='utf-8') as f:
        fr = f.read()
    return yaml.load(fr, Loader=yaml.FullLoader)

APItest.py

class RTSData:

    env = Global.getValue(settings.environment)
    cfg_path = os.path.abspath(os.path.join(os.path.dirname(__file__), f"./rts_{env}.yml"))
    yaml_conf = loadYmlFile(cfg_path)

    host = yaml_conf["host"]
    chain_host = yaml_conf["chain_host"]
    api_id = yaml_conf["api_id"]
    sec_key = yaml_conf["sec_key"]

 

 


 

posted @ 2022-03-07 20:04  他还在坚持嘛  阅读(205)  评论(0编辑  收藏  举报