import yaml
data = {
"str": "Hello world.",
"int": 110,
"list": [10, "she", ["he", "it"]],
"dict": {"account":"xiaoqq", "password": {"pwd1": 123456, "pwd2": "water"}},
"tuple": (100, "a")
}
with open('./writeYamlData.yml', 'w', encoding='utf-8') as f:
yaml.dump(data=data, stream=f, allow_unicode=True)
写入后的yaml文件内容如下:
dict:
account: xiaoqq
password:
pwd1: 123456
pwd2: water
int: 110
list:
- 10
- she
- - he
- it
str: Hello world.
tuple: !!python/tuple
- 100
- a
安装命令:
pip install ruamel.yaml
# 安装速度慢则加上镜像源
pip install ruamel.yaml -i https://pypi.tuna.tsinghua.edu.cn/simple
使用时导入:
from ruamel import yaml
使用yaml.dump()方法写入,代码展示如下:
from ruamel import yaml
data = {
"str": "Hello world.",
"int": 110,
"list": [10, "she", ["he", "it"]],
"dict": {"account":"xiaoqq", "password": {"pwd1": 123456, "pwd2": "water"}},
"tuple": (100, "a")
}
# path为yaml文件的绝对路径
path ='./writeYamlData.yml'
with open(path, 'w', encoding='utf-8') as f:
yaml.dump(data, f, Dumper=yaml.RoundTripDumper)
写入结果如下:
str: Hello world.
int: 110
list:
- 10
- she
- - he
- it
dict:
account: xiaoqq
password:
pwd1: 123456
pwd2: water
tuple:
- 100
- a
注意:这里yaml.dump()里加上l了参数Dumper=yaml.RoundTripDumper。不加该参数则写入结果如下:
dict:
account: xiaoqq
password: {pwd1: 123456, pwd2: water}
int: 110
list:
- 10
- she
- [he, it]
str: Hello world.
tuple: !!python/tuple [100, a]
yaml文件数据如下:
dict:
account: xiaoqq
password:
pwd1: 123456
pwd2: water
int: 110
list:
- 10
- she
- - he
- it
str: Hello world.
tuple: !!python/tuple
- 100
- a
使用yaml.load()方法读取,代码展示如下:
from ruamel import yaml
# path为yaml文件的绝对路径
path ='./writeYamlData.y'
with open(path, 'r', encoding='utf-8') as doc:
content = yaml.load(doc, Loader=yaml.Loader)
print(content)
读取结果如下:
C:\Users\xiaoqq\AppData\Local\Programs\Python\Python37\python.exe C:/Users/xiaoqq/Desktop/test_project/readYaml.py
{'dict': {'account': 'xiaoqq', 'password': {'pwd1': 123456, 'pwd2': 'water'}}, 'int': 110, 'list': [10, 'she', ['he', 'it']], 'str': 'Hello world.', 'tuple': (100, 'a')}
Process finished with exit code 0
ruamel.yaml库继承子PyMYAL库,读写方法基本相同,目前来说可以根据自己的习惯选择使用 ruamel.yaml 还是 PyMYAL 进行yaml文件的读写操作。
如果对软件测试、接口测试、自动化测试、面试经验交流感兴趣可以加入我们。642830685,免费领取最新软件测试大厂面试资料和Python自动化、接口、框架搭建学习资料!技术大牛解惑答疑,同行一起交流。