YAML is a popular data serialization language developed for human readability and interaction. YAML is a powerful tool that offers many features and flexibility, making it a good choice when working with configuration files.

This tutorial shall cover how to work with YAML and a popular scripting language, Python. Python is a great language used in many areas, including automation (such as Ansible), where YAML files find heavy use. Therefore, the ability to work with YAML and Python is a great advantage.

Pre-Requisites

Before we get started on the main tutorial, you will need to have the following requirements fulfilled.

  • Python3 Installed
  • In a position to work with YAML files
  • Some knowledge in Python Programming.

Installing PyYAML

To work with YAML files in Python, we shall use the PyYAML package, a YAML parser, and an emitter for Python Language. It is highly flexible and can apply to various tasks such as configuration files, data serialization, and more.

To install PyYAML on your machine, use pip as shown in the command below:

How to Read a YAML File in Python

For illustration purposes, I will use a pubsec.yaml file available in the Dart Programming language. The contents of the YAML file are below:

name: newtify


version: 1.2.3


description: >


  Have you been turned into a newt?  Would you like to be?


  This package can help. It has all of the


  newt-transmogrification functionality you have been looking


  for.

homepage: https://example-pet-store.com/newtify


documentation: https://example-pet-store.com/newtify/docs


environment:


  sdk: ‘>=2.10.0 <3.0.0'


dependencies:


  efts: ^2.0.4


  transmogrify: ^0.4.0


dev_dependencies:


  test: ‘>=1.15.0 <2.0.0'

Credit: Dart Development Team – https://dart.dev/tools/pub/pubspec

Once we have the file edited and saved, we can use Python to read the values stored in the file.

The first step is to import the yaml package as:

Next, we need to load the YAML file using the safe_load function available in the PyYAML package.

>>> with open(“pubsec.yaml) as f:


             pubsec = yaml.safe_load(f)


        return pubsec

The final step is to put together the code. The full code is as shown below:

import yaml


 

def main():


    with open(“sample.yml”) as f:


        pubsec = yaml.safe_load(f)


    return pubsec


read_yaml = main()


 

print(read_yaml)

From the above code, we start by importing the yaml package. We then create a main function (any name works) and set the logic for reading the yaml file.

Once the file is open and read, we call the main function. At this stage, the YAML file gets converted into a Python dictionary.

If we run the code, we get the output:

{‘name’: ‘newtify’, ‘version’: ‘1.2.3’, ‘description’: ‘Have you been turned into a newt?  Would you like to be? This package can help. It has all of the newt-transmogrification functionality you have been looking for.’, ‘homepage’: ‘https://example-pet-store.com/newtify’, ‘documentation’: ‘https://example-pet-store.com/newtify/docs’, ‘environment’: {‘sdk’: ‘>=2.10.0 <3.0.0'}, ‘dependencies’: {‘efts’: ‘^2.0.4’, ‘transmogrify’: ‘^0.4.0’}, ‘dev_dependencies’: {‘test’: ‘>=1.15.0 <2.0.0'}}

This is not very readable; you can use a package such as pretty print to beautify the dictionary shown above as:

import yaml

import pprint

def main():


    with open(“sample.yml”) as f:


        pubsec = yaml.safe_load(f)


    return pubsec


read_yaml = main()

pprint.pprint(read_yaml)

This will dump the contents as:

{‘dependencies’: {‘efts’: ‘^2.0.4’, ‘transmogrify’: ‘^0.4.0’},


 ‘description’: ‘Have you been turned into a newt?  Would you like to be? This ‘


                ‘package can help. It has all of the newt-transmogrification ‘


                ‘functionality you have been looking for.’,


 ‘dev_dependencies’: {‘test’: ‘>=1.15.0 <2.0.0'},


 ‘documentation’: ‘https://example-pet-store.com/newtify/docs’,


 ‘environment’: {‘sdk’: ‘>=2.10.0 <3.0.0'},


 ‘homepage’: ‘https://example-pet-store.com/newtify’,


 ‘name’: ‘newtify’,


 ‘version’: ‘1.2.3’}

Now that is more readable than before.

How to Read Values from YAML File

To read values from the YAML file above, all we need to do is access the data using the dictionary key.

For example, to read the value of the environment key, we use:

>>> print(read_yaml[‘environment’])

That will give us the value stored in the ‘environment’ key of the read_yaml dictionary. As shown below:

{‘sdk’: ‘>=2.10.0 <3.0.0'}

The output above is a nested dictionary; we can get the actual value by going further the dictionary as:

print(read_yaml[‘environment’][‘sdk’])

This will print the actual value as:

Conclusion

This tutorial has shown you how to read YAML files in Python and read a file’s specific values. That comes in very handy when you need a specific value from a YAML file to perform some operation,

Thank you for reading, and Happy Coding!

About the author

<img alt="" data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2021/07/echo/john-150×150.png" height="112" src="data:image/svg xml,” width=”112″>

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list