简体   繁体   English

如何从纯python创建一个yaml文件?

[英]How can I create a yaml file from pure python?

Example from Using YAML with Python 使用YAML和Python的示例

Original YAML file contains this 原始YAML文件包含此内容

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

After loading the content from the file using yaml.load() , and dump it into a new YAML file, I get this instead: 在使用yaml.load()从文件加载内容并将其转储到新的YAML文件后,我得到了这个:

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

What is the proper way of building up a YAML file straight from pure python? 直接从纯python构建YAML文件的正确方法是什么? I don't want to write string myself. 我不想自己写字符串。 I want to build the dictionary and list. 我想建立字典和列表。


Partial... 部分...

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

OKay. 好的。 I just double checked the documentation. 我只是仔细检查了文档。 We need this at the end of the yaml.dump(data, optional_args) 我们在yaml.dump(data, optional_args)的末尾需要这个

The fix is this 修复就是这个

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

where dataMap is the source yaml.load() and f is the file to be written to. 其中dataMap是源yaml.load() ,f是要写入的文件。

Assuming you are using PyYAML as you probably are, the output you show is not copy-paste of what a yaml.dump() generated as it includes a comment, and PyYAML doesn't write those. 假设您正在使用PyYAML,您显示的输出不是 yaml.dump()生成的内容的复制粘贴,因为它包含注释,而PyYAML不会写这些。

If you want to preserve that comment, as well as eg the key ordering in the file (nice when you store the file in a revision control system) use ¹: 如果要保留该注释,以及例如文件中的键排序(在将文件存储在修订控制系统中时很好),请使用¹:

import ruamel.yaml as yaml

yaml_str = """\
# tree format
treeroot:
    branch1:
        name: Node 1
        branch1-1:
            name: Node 1-1   # should be its own level
    branch2:
        name: Node 2
        branch2-1:
            name: Node 2-1
"""

data = yaml.load(yaml_str, Loader=yaml.RoundTripLoader)
print yaml.dump(data, Dumper=yaml.RoundTripDumper, indent=4)

which gets you exactly the input: 它可以让你完全输入:

# tree format
treeroot:
    branch1:
        name: Node 1
        branch1-1:
            name: Node 1-1   # should be its own level
    branch2:
        name: Node 2
        branch2-1:
            name: Node 2-1

¹ This was done using ruamel.yaml an enhanced version of PyYAML of which I am the author. ¹ 这是使用ruamel.yaml完成的PyYAML的增强版本,我是作者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM