Answers:
import yaml
data = dict(
A = 'a',
B = dict(
C = 'c',
D = 'd',
E = 'e',
)
)
with open('data.yml', 'w') as outfile:
yaml.dump(data, outfile, default_flow_style=False)
该default_flow_style=False
参数对于产生所需的格式(流样式)是必需的,否则对于嵌套集合,它将产生块样式:
A: a
B: {C: c, D: d, E: e}
with
与单线相比,在这里使用有好处吗?
with
确保在不再需要该文件时正确关闭该文件
import yaml; from munch import munchify; f = munchify(yaml.safe_load(…));print(f.B.C)
链接到PyYAML文档,其中显示了default_flow_style
参数的差异。要将其以块模式写入文件(通常更具可读性):
d = {'A':'a', 'B':{'C':'c', 'D':'d', 'E':'e'}}
with open('result.yml', 'w') as yaml_file:
yaml.dump(d, yaml_file, default_flow_style=False)
产生:
A: a
B:
C: c
D: d
E: e
import yaml; from munch import munchify; f = munchify(yaml.safe_load(…));print(f.B.C)