Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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.

1 Answer

0 votes
by (106k points)

If you want to parse/read a YAML file into a Python project and if your YAML file looks like this:

treeroot: 

   branch1: 

      name: Node 1 

 branch1-1:
      name: Node 1-1 

   branch2:

name: Node 2 

branch2-1: 

name: Node 2-1

In that case, you will have to install PyYAML like as follows:-

pip install PyYAML

And the Python code looks like this:

import yaml 

with open('tree.yaml') as f: 

dataMap = yaml.safe_load(f)

Related questions

0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...