写入YAML文件
数据
info = {
'name': 'root',
'age': 18,
'flag': True,
'language': ['C', 'Java', 'Python'],
'other': {
'name': 'Apple',
'date': '2021-08-03',
'product': ['iMac', 'MacBook', 'iPad', 'iPhone']
},
}
使用pyyaml
import yaml
with open('./test.yaml', 'w', encoding='utf8') as f:
yaml.dump(info, f)
结果
正常写入, 但数据无序
age: 18
flag: true
language:
- C
- Java
- Python
name: root
other:
date: '2021-08-03'
name: Apple
product:
- iMac
- MacBook
- iPad
- iPhone
使用ruamle
from ruamel import yaml
with open('./ruamel.yaml', 'w', encoding='utf8') as f:
yaml.dump(info, f, Dumper=yaml.RoundTripDumper, default_flow_style=False, allow_unicode=True)
参数解释
Dumper=yaml.RoundTripDumper: 保证能够按照顺序保存
default_flow_style=False: False表示不保存默认格式, 列表和字典按照yaml的格式保存 而不是直接保存[]和{}
allow_unicode=True: 上传格式以unicode
结果
正常写入, 并且顺序与info的顺序完全一致
name: root
age: 18
flag: true
language:
- C
- Java
- Python
other:
name: Apple
date: '2021-08-03'
product:
- iMac
- MacBook
- iPad
- iPhone
读取YAML文件
使用pyyaml
import yaml
with open('./test.yaml', 'r', encoding='utf8') as f:
data = yaml.load(f, Loader=yaml.Loader)
结果
{'age': 18, 'flag': True, 'language': ['C', 'Java', 'Python'], 'name': 'root', 'other': {'date': '2021-08-03', 'name': 'Apple', 'product': ['iMac', 'MacBook', 'iPad', 'iPhone']}}
使用ruamel
from ruamel import yaml
with open('./ruamel.yaml', 'r', encoding='utf8') as f:
data = yaml.load(f, Loader=yaml.RoundTripLoader)
结果
{'name': 'root', 'age': 18, 'flag': True, 'language': ['C', 'Java', 'Python'], 'other': ordereddict([('name', 'Apple'), ('date', '2021-08-03'), ('product', ['iMac', 'MacBook', 'iPad', 'iPhone'])])}
结论
综上比较, 推荐使用ruamel模块处理YAML文件