How to parse/read a YAML file into a Python object?
For example, this YAML:
Person:
name: XYZ
To this Python class:
class Person(yaml.YAMLObject):
yaml_tag = 'Person'
def __init__(self, name):
self.name = name
I am using PyYAML by the way.
Best Answer
If your YAML file looks like this:
And you've installed
PyYAML
like this:And the Python code looks like this:
The variable
dataMap
now contains a dictionary with the tree data. If you printdataMap
using PrettyPrint, you will get something like:So, now we have seen how to get data into our Python program. Saving data is just as easy:
You have a dictionary, and now you have to convert it to a Python object:
Then you can use:
and follow "Convert Python dict to object".
For more information you can look at pyyaml.org and this.