How to read Yaml with Python?

Asked

Viewed 648 times

5

How do I read a Yaml file or code with Python?

You need to install something, or you can do it natively?

Example:

fruits:
    - Apple
    - Orange
    - Strawberry
    - Mango

1 answer

6


You have to install the module if you don’t have it:

sudo pip install pyyaml

Might not need the sudo, depending on the system.

And then:

import yaml

with open("tests.yaml", 'r') as f:
    try:
        print(yaml.load(f))
    except yaml.YAMLError as exc:
        print(exc)

Output for what you placed:

{'Fruits': ['Apple', 'Orange', 'Strawberry', 'Mango']}

DOCS

  • +1. I tested here and it worked right :p

  • :p.. Still good @Wallacemaxters. I also had not installed it, had to install it to test

  • I liked the library because it seems to follow the same pattern as the json.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.