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.
Reading a key from YAML config file We can read the data using yaml. load() method which takes file pointer and Loader as parameters. FullLoader handles the conversion from YAML scalar values to the Python dictionary. The index [0] is used to select the tag we want to read.
Adding YAML Support to Python Meaning, Python cannot read or interpret YAML documents by default. To add YAML support to Python, you have first to install the PyYAML module. To install the PyYAML module, you'll need to run the pip command, which is the package installer for Python.
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
And you've installed PyYAML
like this:
pip install PyYAML
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)
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' } } }
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)
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)
Then you can use:
>>> args = your YAML dictionary >>> s = Struct(**args) >>> s <__main__.Struct instance at 0x01D6A738> >>> s...
and follow "Convert Python dict to object".
For more information you can look at pyyaml.org and this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With