9

将 YAML 与 Python 结合使用的示例

原始 YAML 文件包含此

# 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 文件中后,我得到了这个:

# 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 文件的正确方法是什么?我不想自己写字符串。我想建立字典和列表。


部分的...

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

3 回答 3

8

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

修复是这样的

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

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

于 2012-02-03T21:20:18.593 回答
2

假设您可能正在使用 PyYAML,您显示的输出不是生成的内容的复制粘贴,yaml.dump()因为它包含注释,并且 PyYAML 不会编写这些内容。

如果您想保留该注释,以及例如文件中的键顺序(当您将文件存储在修订控制系统中时很好),请使用 ¹:

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)

这可以让你准确地输入:

# 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

¹这是使用ruamel.yaml完成的,我是 PyYAML 的增强版本。

于 2015-07-01T03:17:48.053 回答
1

您的第一个和第二个列表是等效的,只是符号不同。

请参阅:http ://en.wikipedia.org/wiki/YAML#Associative_arrays和http://pyyaml.org/wiki/PyYAMLDocumentation#Dictionarieswithoutnestedcollectionsarenotdumpedcorrectly

于 2012-02-03T21:26:33.143 回答