python解析配置文件ini、yaml

python解析配置文件ini、yaml

解决方案goocz2025-06-29 5:53:341A+A-

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

解析ini文件

使用configparser模块,python自带的不需要安装

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]) #返回内容

解析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)
点击这里复制本文地址 以上内容由goocz整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!

果子教程网 © All Rights Reserved.  蜀ICP备2024111239号-5