如何将YAML格式的数据写入文件?


Answers:


195
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}

14
default_flow_style = True与下面的答案相反!
encc 2014年

with与单线相比,在这里使用有好处吗?
src

2
@src with确保在不再需要该文件时正确关闭该文件
kbolino

参见Munchstackoverflow.com import yaml; from munch import munchify; f = munchify(yaml.safe_load(…));print(f.B.C)
questions/52570869/…

76

链接到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

参见Munchstackoverflow.com import yaml; from munch import munchify; f = munchify(yaml.safe_load(…));print(f.B.C)
questions/52570869/…
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.