# encoding=utf-8
import os
import yaml
adict = {
'a': 1,
'b': {'c: 3'},
'result': True
}
with open('ly_yaml.yaml', 'w', encoding='utf-8') as f:
yaml.dump(adict, f)
'''
a: 1
b: !!set
'c: 3': null
result: true
'''
with open('ly_yaml.yaml', 'r', encoding='utf-8') as f:
aa = yaml.load(f.read())
print(aa) # {'a': 1, 'b': {'c: 3'}, 'result': True}
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
from ruamel import yaml # pip install ruamel.yaml
with open('ly_yaml_1.yaml', 'w', encoding='utf-8') as f:
yaml.dump(adict, f, Dumper=yaml.RoundTripDumper)
'''
a: 1
b: !!set
'c: 3':
result: true
'''
with open('ly_yaml_1.yaml', 'r', encoding='utf-8') as f:
aa = yaml.load(f.read(), Loader=yaml.Loader)
print(aa) # {'a': 1, 'b': {'c: 3'}, 'result': True}
python读写yaml文件
于 2021-02-03 11:30:11 首次发布