我有两个 python 字典,我想将它们写入一个 yaml 文件,其中包含两个文档:
definitions = {"one" : 1, "two" : 2, "three" : 3}
actions = {"run" : "yes", "print" : "no", "report" : "maybe"}
yaml 文件应如下所示:
--- !define
one: 1
two: 2
three: 3
-- !action
run: yes
print: no
report: maybe
...
使用 PyYaml 我没有找到明确的方法来做到这一点。我确信有一个简单的方法,但深入研究 PyYaml 文档只会让我感到困惑。我需要自卸车、发射器还是什么?这些类型各自产生什么类型的输出? yaml 文本? yaml 节点? YAML 对象?无论如何,我将不胜感激任何澄清。
根据下面 unutbu 的回答,这是我能想到的最简洁的版本:
DeriveYAMLObjectWithTag 是一个用于创建新类的函数,该新类派生自带有所需标签的 YAMLObject:
def DeriveYAMLObjectWithTag(tag):
def init_DeriveYAMLObjectWithTag(self, **kwargs):
""" __init__ for the new class """
self.__dict__.update(kwargs)
new_class = type('YAMLObjectWithTag_'+tag,
(yaml.YAMLObject,),
{'yaml_tag' : '!{n}'.format(n = tag),
'__init__' : init_DeriveYAMLObjectWithTag})
return new_class
以下是如何使用 DeriveYAMLObjectWithTag 获取所需的 Yaml:
definitions = {"one" : 1, "two" : 2, "three" : 3, "four" : 4}
actions = {"run" : "yes", "print" : "no", "report" : "maybe"}
namespace = [DeriveYAMLObjectWithTag('define')(**definitions),
DeriveYAMLObjectWithTag('action')(**actions)]
text = yaml.dump_all(namespace,
default_flow_style = False,
explicit_start = True)
感谢所有回答的人。我似乎 PyYaml 缺乏功能,这是克服它的最优雅的方法。