How can I create a yaml file from pure python?

强颜欢笑 提交于 2021-02-07 12:20:14

问题


Example from Using YAML with Python

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

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

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.


Partial...

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

回答1:


OKay. I just double checked the documentation. We need this at the end of the 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.




回答2:


Your first and second listings are equivalent, just different notation.

See: http://en.wikipedia.org/wiki/YAML#Associative_arrays and http://pyyaml.org/wiki/PyYAMLDocumentation#Dictionarieswithoutnestedcollectionsarenotdumpedcorrectly




回答3:


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.

If you want to preserve that comment, as well as e.g 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.



来源:https://stackoverflow.com/questions/9135275/how-can-i-create-a-yaml-file-from-pure-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!