python解析配置文件ini、yaml
我们经常会用到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)
相关文章
- YAMLException: 解决java.nio.charset.MalformedInputException
- 如何校验K8S Yaml文件
- springboot整合redisson(一)搭建Redisson环境
- python unittest框架参数化学习
- x-cmd pkg | yq - 命令行 YAML处理工具
- Kubernetes:通过轻量化工具 kubespy 实时观察YAML资源变更
- Docker新手福音!这个开源控制面板让你更快上手Docker
- 如何搭建接口自动化测试框架?
- Spring Boot中通过@PropertySource注解读取yaml或yml配置文件
- Python 自动化处理 Yaml 文件