Categories
Python Answers

How to parse a YAML file in Python?

Spread the love

Sometimes, we want to parse a YAML file in Python.

In this article, we’ll look at how to parse a YAML file in Python.

How to parse a YAML file in Python?

To parse a YAML file in Python, we can use the PyYAML package.

To install it, we run:

pip install pyyaml

Then we write:

import yaml

with open("example.yaml", "r") as stream:
    try:
        print(yaml.safe_load(stream))
    except yaml.YAMLError as exc:
        print(exc)

to parse example.yaml, which has:

a list:
- 1
- 42
- 3.141
- 1337
- help
- €
a string: bla
another dict:
  foo: bar
  key: value
  the answer: 42

We open the YAML file with open with read permission.

Then we call yaml.safe_load to load the open file stream.

From print, we get:

{'a list': [1, 42, 3.141, 1337, 'help', '€'], 'a string': 'bla', 'another dict': {'foo': 'bar', 'key': 'value', 'the answer': 42}}

A yaml.YAMLError will be raised if the file can’t be parsed.

Conclusion

To parse a YAML file in Python, we can use the PyYAML package.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *