yaml⽂件读取load()、写⼊dump()
yaml简介
1、yaml [ˈjæməl]: Yet Another Markup Language :另⼀种标记语⾔。yaml 是专门⽤来写配置⽂件的语⾔,⾮常简洁和强⼤。它实质上是⼀种通⽤的数据串⾏化格式。YAML 是⼀种⾮常灵活的格式,⼏乎是 JSON 的超集。除了⽀持注释、换⾏符分隔、多⾏字符串、裸字符串和更灵活的类型系统之外,YAML 也⽀持引⽤⽂件,以避免重复代码。
2、在⾃动化测试中,通常使⽤yaml⽂件来编写⾃动化测试⽤例。例如:
3、yaml基本语法规则:
⼤⼩写敏感
使⽤缩进表⽰层级关系
缩进时不允许使⽤Tab键,只允许使⽤空格。
缩进的空格数⽬不重要,只要相同层级的元素左侧对齐即可
#表⽰注释,从这个字符⼀直到⾏尾,都会被解析器忽略,这个和python的注释⼀样
4、yaml⽀持的数据结构有三种:
对象:键值对的集合,⼜称为映射(mapping)/ 哈希(hashes) / 字典(dictionary)
数组:⼀组按次序排列的值,⼜称为序列(sequence) / 列表(list)
纯量(scalars):单个的、不可再分的值。字符串、布尔值、整数、浮点数、Null、时间、⽇期
5、python中,⽂件后缀名为.yml与.yaml的⽂件表⽰作⽤相同,即yaml⽂件;⼀般来说,最常⽤的使⽤.yml作为yaml⽂件后缀名。例如:
安装yaml
使⽤pip安装pyyaml模块:
pip install pyyaml
yaml⽂件⽀持的数据结构举例
1、yaml⾥⾯的键值对,也就是python⾥⾯的字典(dict)数据类型;⽐如python字典:
# python3.6
{
"user": "admin",
"psw": "123456,
}
在yaml⽂件⾥可以这样写:
# yaml
user: admin
psw: 123456
2、字典嵌套字典:
# python3.6
"nb1": {
"user": "admin",
"psw": "123456,
}
yaml⽂件⾥可以这样写:
# yaml
nb1:
user: admin
psw: 123456
yaml⽂件中的序列(list)
yaml⽂件⾥⾯写⼀个数组,需要在前⾯加⼀个‘-’符号。如下:
-
admin1: 123456
- admin2: 111111
- admin3: 222222
对应python⾥⾯的list数据类型:
[{'admin1': 123456}],
[{'admin2': 111111}],
[{'admin3': 222222}]
注意:数字读出来的是int或float类型
yaml⽂件中的纯量(str)
1、int和float类型的数字
n1: 12.30
对应python中的
{'n1': 12.3}
2、布尔值⽤true和false表⽰
n3: false
对应python中的
{'n2': True, 'n3': False}
注意:与从⽂本中读出来的json格式的字符串通过反序列化转为python数据类型相同。3、None⽤~表⽰。
n4: ~
对应python中的
{'n4': None}
注意:从⽂本中读取出来的json格式的字符串是null的时候转换成python数据类型是None。
4、时间采⽤ ISO8601 格式
time1: 2001-12-14t21:59:43.10-05:00
对应python中的
{'time1': datetime.datetime(2001, 12, 15, 2, 59, 43, 100000)}
5、⽇期采⽤复合 iso8601 格式的年、⽉、⽇表⽰。
date1: 2017-07-31
对应python中的
{'date1': datetime.date(2017, 7, 31)}
6、使⽤两个感叹号,强制转换数据类型。
# int转str
n6: !!str 123
对应python中的
{'n6': '123'}
# bool值转str
n7: !!str true
对应python中的
{'n7': 'true'}
举例:在yaml⽂件写⼊以下内容:
n1: 12.30
n2: true
n3: false
n4: ~
time1: 2018-04-18t21:59:43.10+08:00
date1: 2018-04-18
n6: !!str 123
n7: !!str true
python读取结果:
{'n1': 12.3,
'n2': True,
'n3': False,
'n4': None,
'time1': datetime.datetime(2018, 4, 18, 13, 59, 43, 100000),
'date1': datetime.date(2018, 4, 18),
'n6': '123',
'n7': 'true'}
混合使⽤
1、list嵌套dict,在yaml⾥⾯写⼊如下内容:
- user: admin1
psw: '123456'
- user: admin2
psw: '111111'
- user: admin3
psw: '222222'
⽤python读取出来的结果:
[{'user': 'admin1', 'psw': '123456'},
{'user': 'admin2', 'psw': '111111'},
{'user': 'admin3', 'psw': '222222'}]
2、dict嵌套list,在yaml⾥⾯写⼊如下内容:
nub1:
- admin1
- '123456'
nb2:
- admin2
- '111111'
nb3:
-
admin3
⽤python读取出来的结果:
{'nub1': ['admin1', '123456'],
'nb2': ['admin2', '111111'],
'nb3': ['admin3', '222222']}
使⽤python的load()⽅法读取yaml⽂件内容【反序列化】
data=yaml.load(f,Loader=yaml.FullLoader)
在 yaml.load ⽅法中, loader 参数有四种:
①BaseLoader:载⼊⼤部分的基础YAML
②SafeLoader:载⼊YAML的⼦集,推荐在不可信的输⼊时使⽤
③FullLoader:这是默认的载⼊⽅式,载⼊全部YAML
④UnsafeLoader:⽼版本的载⼊⽅式
注意:
需要加上参数: Loader=yaml.FullLoader
如图:
举例1:
import yaml
def main():
with open("./data.yaml","r") as f:
data=yaml.load(f,Loader=yaml.FullLoader)
print(data)
if__name__ == '__main__':
main()
举例2:
# coding:utf-8
import yaml
import os
# 获取当前脚本所在⽂件夹路径
curPath = os.path.dirname(alpath(__file__))
# 获取yaml⽂件路径
yamlPath = os.path.join(curPath, "cfgyaml.yaml")
# open⽅法打开直接读出来
f = open(yamlPath, 'r', encoding='utf-8')
cfg = f.read()
print(type(cfg))  # 读出来是字符串
print(cfg)
d = yaml.load(cfg,Loader=yaml.FullLoader) # ⽤load⽅法将json字符串转换字典类型
print(d) print(type(d))
运⾏结果:
使⽤python的safe_load()⽅法读取yaml⽂件内容【反序列化】使⽤ yaml.safe_load() ⽅法,这个只解析基本的yaml标记,⽤来保证代码的安全性,不过这对于平常保存数据是⾜够了。
源码如下:
def safe_load(stream):
"""
Parse the first YAML document in a stream
and produce the corresponding Python object.
Resolve only basic YAML tags. This is known
to be safe for untrusted input.
"""
return load(stream, SafeLoader)
def load(stream, Loader=None):
spring怎么读取yaml
"""
Parse the first YAML document in a stream
and produce the corresponding Python object.
"""
if Loader is None:
load_warning('load')
Loader = FullLoader
loader = Loader(stream)
try:
_single_data()
finally:
loader.dispose()
可以看到 safe_load() ⽅法就是在load⽅法中传⼊SafeLoader的解析器,那么yaml有些什么Loader呢?
①UnsfeLoader & Loader
The original Loader code that could be easily exploitable by untrusted data input.
②SafeLoader:
Loads a subset of the YAML language, safely. This is recommended for loading untrusted input.
安全的加载yaml语⾔⼦集,对于加载不受信任的输⼊,推荐使⽤此种⽅式 yaml.safe_load()
③FullLoader:
Loads the full YAML language. Avoids arbitrary code execution. This is currently (PyYAML 5.1) the default loader called by yaml.load(input) (after issuing the warning).
加载完整的yaml语⾔,从上⽅的源码可以看出这个是loade()默认的加载⽅式
④BaseLoader:
Only loads the most basic YAML
只加载最基本的yaml
safe_load()⽅法举例:
代码如下:
import yaml
from string import Template
def yaml_template(data: dict):
with open("a.yml", encoding="utf-8") as f:
re = ad()).substitute(data)
return yaml.load(stream=re, Loader=yaml.FullLoader)
if__name__ == '__main__':
print(yaml_template({'token': 'hdadhh21uh1283hashdhuhh2hd', 'username': 'admin', 'password': '123456'}))
运⾏结果:
{'method': 'get', 'url': 'www.baidu', 'headers': {'Content-Type': 'application/json', 'token': 'hdadhh21uh1283hashdhuhh2hd'}, 'data': {'username': 'admin', 'password': 123456}}使⽤python的dump()⽅法将python字典写⼊yaml⽂件【序列化】yaml.dump(data,f,encoding='utf-8',allow_unicode=True)
当data数据中有汉字时,加上: encoding='utf-8',allow_unicode=True
举例:
import os
import yaml
yaml_dict = {
"user": "general",
"country": "China",
"gender": "male",
"address": "北京"
}
yaml_dir = os.path.join(os.path.dirname(alpath(__file__)), 'a.yml')
with open(yaml_dir, 'w', encoding='utf-8', ) as f:
yaml.dump(yaml_dict, f, encoding='utf-8', allow_unicode=True)
运⾏结果:
如果在写⼊yaml⽂件不加 encoding='utf-8',allow_unicode=True 参数时,即:
import os
import yaml
yaml_dict = {
"user": "general",
"country": "China",
"gender": "male",
"address": "北京"
}
yaml_dir = os.path.join(os.path.dirname(alpath(__file__)), 'a.yml')
with open(yaml_dir, 'w', encoding='utf-8', ) as f:
yaml.dump(yaml_dict, f)
运⾏结果:
如上图,如果在写⼊yaml⽂件不加 encoding='utf-8',allow_unicode=True可以看到汉字是以unicode码写⼊到yaml⽂件当中。
在实际使⽤的时候可以配合,输⼊参数更新配置⽂件中的参数使⽤:def merge_config(config,args):
for key_1 in config.keys():
if(isinstance(config[key_1],dict)):
for key_2 in config[key_1].keys():
if(key_2) in dir(args):
config[key_1][key_2] = getattr(args,key_2)
return config
config = yaml.load(fig, 'r', encoding='utf-8'),Loader=yaml.FullLoader) config = merge_config(config,args)

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。