如果您的YAML文件如下所示:
# tree formattreeroot: branch1: name: Node 1 branch1-1: name: Node 1-1 branch2: name: Node 2 branch2-1: name: Node 2-1
并且您已经这样安装
PyYAML:
pip install PyYAML
Python代码如下所示:
import yamlwith open('tree.yaml') as f: # use safe_load instead load dataMap = yaml.safe_load(f)变量
dataMap现在包含带有树数据的字典。如果
dataMap使用PrettyPrint打印,则会得到类似以下内容的信息:
{'treeroot': {'branch1': {'branch1-1': {'name': 'Node 1-1'}, 'name': 'Node 1'}, 'branch2': {'branch2-1': {'name': 'Node 2-1'}, 'name': 'Node 2'}}}因此,现在我们已经了解了如何将数据获取到我们的Python程序中。保存数据同样简单:
with open('newtree.yaml', "w") as f: yaml.dump(dataMap, f)您有一个字典,现在必须将其转换为Python对象:
class Struct: def __init__(self, **entries): self.__dict__.update(entries)
然后,您可以使用:
>>> args = your YAML dictionary>>> s = Struct(**args)>>> s<__main__.Struct instance at 0x01D6A738>>>> s...
并遵循“将Python字典转换为对象”。
有关更多信息,请访问pyyaml.org和this。



