使用库 :import yaml
安装:pip install pyyaml
示例:
文件config2.yml
guard_url : 'https://www.xxxx.com'
app :chrome_files : 'C:\Program Files\Google\Chrome\Application\chrome.exe'
networkTime : 30
title : '公司'
读取yml数据
def read_yml(file):"""读取yml,传入文件路径file"""f = open(file,'r',encoding="utf-8") # 读取文件yml_config = yaml.load(f,Loader=yaml.FullLoader) # Loader为了更加安全"""Loader的几种加载方式BaseLoader - -仅加载最基本的YAMLSafeLoader - -安全地加载YAML语言的子集。建议用于加载不受信任的输入。FullLoader - -加载完整的YAML语言。避免任意代码执行。这是当前(PyYAML5.1)默认加载器调用yaml.load(input)(发出警告后)。UnsafeLoader - -(也称为Loader向后兼容性)原始的Loader代码,可以通过不受信任的数据输入轻松利用。"""return yml_config
打印yml内容
yml_info=read_yml('config.yml')
print(yml_info['guard_url'])
print(yml_info['app'])
print((yml_info['app'])['chrome_files'])"""
https:xxxx.com
{'chrome_files': 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe'}
C:\Program Files\Google\Chrome\Application\chrome.exe
"""
插入到yml数据
def write_yml(file,data):# 写入数据:with open(file, "a",encoding='utf-8') as f:# data数据中有汉字时,加上:encoding='utf-8',allow_unicode=Truef.write('\n') # 插入到下一行yaml.dump(data, f, encoding='utf-8', allow_unicode=True)data = {"S_data": {"test1": "hello"}, "Sdata2": {"name": "汉字"}}
write_yml('config2.yml',data=data)
更新yml的数值
逻辑是完整读取然后更新数值后在完整写入。
def read_yml(file):"""读取yml,传入文件路径file"""f = open(file, 'r', encoding="utf-8") # 读取文件yml_config = yaml.load(f, Loader=yaml.FullLoader) # Loader为了更加安全return yml_config
def updata_yaml(file):"""更新yml的数值"""old_data=read_yml(file) #读取文件数据old_data['title']='仔仔大哥哥' #修改读取的数据(with open(file, "w", encoding="utf-8") as f:yaml.dump(old_data,f,encoding='utf-8', allow_unicode=True)
updata_yaml('config2.yml')