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

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

我需要使用Python将以下数据写入yaml文件:

{A:a, B:{C:c, D:d, E:e}} 

即字典中的字典。我该如何实现?

I need to write the below data to yaml file using Python:

{A:a, B:{C:c, D:d, E:e}} 

i.e., dictionary in a dictionary. How can I achieve this?


回答 0

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

The default_flow_style=False parameter is necessary to produce the format you want (flow style), otherwise for nested collections it produces block style:

A: a
B: {C: c, D: d, E: e}

回答 1

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

Link to the PyYAML documentation showing the difference for the default_flow_style parameter. To write it to a file in block mode (often more readable):

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)

produces:

A: a
B:
  C: c
  D: d
  E: e