python 读取yaml文件
简介
在实际开发过程中,我们可能需要读取一些配置文件的配置信息,例如ini、yaml、property等格式,本文将讲述怎么去获取和设置yaml文件的相关参数。
示例yaml文件
test1:
test2-1: 5
test2-2: 130000
test2-3:
test3-1: 123
test3-2: 256
使用到的模块
pip3 install PyYAML
读写yaml文件
import yaml, os, json
class YamlUtil():
def __init__(self, yaml_path):
self.yaml_path = yaml_path
def get_yml_data(self, is_modify=False, *key_names):
"""
读取yaml配置文件并根据对应层级的key获取对应的value
适用于两层数据
:param: key_names: 需要查询的yaml文件的key关键字,从左向右依次
:return: result: 根据key值返回对应value,不传key则直接返回所有, 没有对应key则返回None
"""
with open(self.yaml_path, "r", encoding="utf-8") as f:
content = f.read()
yaml_content = yaml.safe_load(content)
if is_modify:
return yaml_content
try:
for key_name in key_names:
yaml_content = yaml_content.get(key_name, None)
return yaml_content
except Exception as e:
print(f"get_yml_data error:{e}")
return None
def set_yaml_data(self, value, *key_names):
"""
设置yaml文件中的相关属性
:param: value:修改后的值
:param: key_names: 需要修改的yaml文件的key关键字,从左向右依次
"""
yaml_content = self.get_yml_data(True, key_names)
print(f'yaml_content:before:{yaml_content}')
key_name = ''
for item in list([[item] for item in key_names]):
key_name += str(item)
print(f'key_name:{key_name}')
command = "yaml_content" + key_name + '=' + str(value)
print(f'command:{command}')
# exec:将字符串转换成python代码执行
exec(command)
print(f'yaml_content:after:{yaml_content}')
with open(self.yaml_path, mode='w', encoding='utf-8') as f:
f.write(yaml.safe_dump(yaml_content))
if __name__ == '__main__':
YAML_PATH = os.path.join(os.path.dirname(__file__), 'test.yaml')
yamlUtil = YamlUtil(YAML_PATH)
print(yamlUtil.get_yml_data("test1", "test2-1"))
print(yamlUtil.get_yml_data("test1", "test2-3", "test3-1"))
yamlUtil.set_yaml_data(123, "test1", "test2-1")
yamlUtil.set_yaml_data(111, "test1", "test2-3", "test3-1")
获取属性采用的是将数据读取出来成字典,然后直接取出对应属性即可,设置属性采用的是读取原有数据,使用字典更新对应值的方式,不过是采用exec执行拼接的字符串方式。