How to read Yaml with Python?

4

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

Is it necessary to install anything, or can you do it natively?

Example:

fruits:
    - Apple
    - Orange
    - Strawberry
    - Mango
    
asked by anonymous 16.11.2016 / 11:50

1 answer

5

You have to install the module if you do not have it:

sudo pip install pyyaml

sudo may not be required, 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 to what you put:

  

{'fruits': ['Apple', 'Orange', 'Strawberry', 'Mango')}

DOCS

    
16.11.2016 / 11:59