如何从纯 python 创建 yaml 文件? [英] How can I create a yaml file from pure python?

查看:39
本文介绍了如何从纯 python 创建 yaml 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自在 Python 中使用 YAML 的示例

原始 YAML 文件包含此

Original YAML file contains this

# tree format
treeroot:
    branch1:
        name: Node 1
        branch1-1:
            name: Node 1-1
    branch2:
        name: Node 2
        branch2-1:
            name: Node 2-1

使用 yaml.load() 从文件加载内容并将其转储到新的 YAML 文件后,我得到了这个:

After loading the content from the file using yaml.load() , and dump it into a new YAML file, I get this instead:

# tree format
treeroot:
    branch1:
        branch1-1: {name:Node 1-1}
        name: Node 1
    branch2:
        branch2-1: {name: Node 2-1}
        name: Node 2

直接从纯 python 构建 YAML 文件的正确方法是什么?我不想自己写字符串.我想建立字典和列表.

What is the proper way of building up a YAML file straight from pure python? I don't want to write string myself. I want to build the dictionary and list.

部分...

dataMap = {'treeroot':
               {'branch2': 
                 {'branch1-1': 
                  {'name': 'Node 1-1'},   # should be its own level
                  'name': 'Node 1'
                 }
               }
          }

推荐答案

好的.我只是仔细检查了文档.我们需要在 yaml.dump(data, optional_args)

OKay. I just double checked the documentation. We need this at the end of the yaml.dump(data, optional_args)

解决办法是这样

yaml.dump(dataMap, f, default_flow_style=False)

其中 dataMap 是源 yaml.load(),f 是要写入的文件.

where dataMap is the source yaml.load() and f is the file to be written to.

这篇关于如何从纯 python 创建 yaml 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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