如何将YAML文件解析/读入Python对象? [英] How to parse/read a YAML file into a Python object?
问题描述
如何将YAML文件解析/读入Python对象?
How to parse/read a YAML file into a Python object?
例如,此YAML:
Person:
name: XYZ
此Python类:
class Person(yaml.YAMLObject):
yaml_tag = 'Person'
def __init__(self, name):
self.name = name
我正在使用PyYAML.
I am using PyYAML by the way.
推荐答案
如果您的YAML文件如下所示:
If your YAML file looks like this:
# tree format
treeroot:
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代码如下:
And the Python code looks like this:
import yaml
with open('tree.yaml') as f:
# use safe_load instead load
dataMap = yaml.safe_load(f)
变量dataMap
现在包含一个包含树数据的字典.如果使用PrettyPrint打印dataMap
,您将得到类似的信息:
The variable dataMap
now contains a dictionary with the tree data. If you print dataMap
using PrettyPrint, you will get something like:
{'treeroot': {'branch1': {'branch1-1': {'name': 'Node 1-1'},
'name': 'Node 1'},
'branch2': {'branch2-1': {'name': 'Node 2-1'},
'name': 'Node 2'}}}
因此,现在我们已经了解了如何将数据获取到我们的Python程序中.保存数据同样简单:
So, now we have seen how to get data into our Python program. Saving data is just as easy:
with open('newtree.yaml', "w") as f:
yaml.dump(dataMap, f)
您有一个字典,现在您必须将其转换为Python对象:
You have a dictionary, and now you have to convert it to a Python object:
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 dict转换为对象".
有关更多信息,请参见 pyyaml.org 和
For more information you can look at pyyaml.org and this.
这篇关于如何将YAML文件解析/读入Python对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!