【发布时间】:2016-07-18 20:36:32
【问题描述】:
我有一个简单的数据结构,我需要将其转储到 YAML 文件中,并在开头添加一个带有 !v2 行的类型标记。
如何使用 PyYAML 库做到这一点?
import yaml
class MyDumper(yaml.SafeDumper):
# ???
# somehow add a "!v2" type tag at the beginning
y = {'foo': 3, 'bar': 'haha', 'baz': [1,2,3]}
with open(myfile, 'w') as f:
# a hack would be to write the "!v2" here,
# outside the normal yaml.dump process,
# but I'd like to learn the right way
yaml.dump(f, y, Dumper=MyDumper)
【问题讨论】: