如何在YAML格式的文件中写入数据? [英] How can I write data in YAML format in a file?

查看:897
本文介绍了如何在YAML格式的文件中写入数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

即词典中的字典。

解决方案

  import yaml 

data = dict(
A ='a',
B = dict(
C ='c',
D ='d',
E ='e ',



打开('data.yml','w')作为outfile:
yaml.dump(data,outfile,default_flow_style = False)

default_flow_style = False 参数是需要产生你想要的格式(流风格),否则为嵌套集合它会产生块样式:

$ $ p $ $ code $ 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?

解决方案

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}

这篇关于如何在YAML格式的文件中写入数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆