In this tutorial, We are going to learn yaml parsing in python examples

How t install the yaml package for Python?

There are number of libraries available to parse yaml in python First, Search for yaml packages using pi search command

pip search yaml

This lists following available packages

  • PyYAML
  • yamltools
  • PySyck

[pyyaml](https://pyyaml.org/wiki/PyYAMLDocumentation) is an upto date python yaml module for reading and writing yaml files.

First, Installs pyyaml library using pip package manager In windows,

pip install pyyaml

In linux or ubuntu

sudo apt-get install PyYAML  // ubuntu
sudo yum install PyYAML  //linux
sudo aptitude install // debinal OS flavour

How to read YAML file in python

Let’s see an multiple examples to read yaml file and store it in object.

Sample Yaml file read example

yaml is superset of json. It contains key and value pairs with included indentation and tabs.

Given the config.yaml example file with database dictionary configuration details.

--- # Application configuration - config.yaml
author: Franc
database:
        driver: com.mysql.jdbc.Driver
        port: 3306
        dbname: mydb
        username: root
        password: 

Here is an example code to read yaml file into object

import yaml

with open('config.yaml') as file:
    try:
        databaseConfig = yaml.safe_load(file)   
        print(databaseConfig)
    except yaml.YAMLError as exc:
        print(exc)

Output:

{'author': 'Franc', 'database': {'driver': 'com.mysql.jdbc.Driver', 'port': 3306, 'dbname': 'mydb', 'username': 'root', 'password': None}}

Here are steps

  • First import yaml module using import statement
  • Read the file using open method
  • safe_load method read the file content and convert to dictionary pyhton object
  • enclose file reading try and expect block to hand exceptions

Let’s see another example for reading array of yaml data

python parser to read array of strings yaml data example

An sample yaml file - data.yaml which contains array of strings

weekday:

  - monday
  - tuesday
  - wednesday
  - thursday
  - friday
  - saturday
  - sunday
months:

  - jan
  - feb
  - mar
  - apr
  - may
  - june
  - july

Let’s see an python code

import yaml

with open('data.yaml') as file:
    try:
        data = yaml.safe_load(file)
        for key, value in data.items():
            print(key, ":", value)
    except yaml.YAMLError as exception:
        print(exception)

Output:

weekday : ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
months : ['jan', 'feb', 'mar', 'apr', 'may', 'june', 'july']

Sequence of Steps

  • import yaml module
  • read file and store data in data variable
  • Iterate keys and values using for loop
  • print key and values
  • enclose try and except block for yaml file read

write dictionary into yaml file in python

  • load yaml module into python file
  • Declare dictionary of objects with data
  • Open file for write data
  • yaml module dump method writes data to an file

Here is an example to write yaml dictionary into an file

import yaml

days = [{'weekday' : ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']},
{'months' : ['jan', 'feb', 'mar', 'apr', 'may', 'june', 'july']}]

with open(r'output.yaml', 'w') as file:

    outputs = yaml.dump(days, file)
    prints outputs
- weekday:
  - monday
  - tuesday
  - wednesday
  - thursday
  - friday
  - saturday
  - sunday
- months:
  - jan
  - feb
  - mar
  - apr
  - may
  - june
  - july