Skip to main content
Yaml-File-Read-and-write-Example

How To Read Write Yaml File in Python3

This tutorial will show you how to read and write YAML files in Python. For reading and writing data from and to YAML files, I use the ruamel.yaml python libs. YAML stands for Yet Another Markup Language.

The easiest and purest method without relying on C headers is PyYaml, which can be installed by the following command –

pip install pyyaml

You can also checkout other python File tutorials:

The ruamel is wrapped on top of the pyyaml libs. This is a YAML parser/emitter that allows for roundtrip comment preservation, seq/map flow style, and map key order.

Many of the bugs filed against PyYAML, but that was never acted upon, have been fixed in ruamel.yaml

We can install the package using the following command –

py install ruamel.yaml

How To Read Yaml File in Python

We will import ruamel package and then load yaml file. You can pass absolute url or full path of yaml file.

from ruamel.yaml import YAML
yaml=YAML()
data = yaml.load(c:\workflow\test.yaml)
print(data)

How To Write Yaml File

We can dump the data into yaml file as well, The library has a dump() to write data into the file.

from ruamel.yaml import YAML
yaml=YAML()
data = yaml.dump(data, c:\workflow\test_updated.yaml)
print(data)

How To Iterate On Yaml File Data

We can iterate on yaml data as like other dict type data –

for key in doc: 
   print(doc[key])

In the above code, We are writing data into the c:\workflow\test_updated.yaml file.

Leave a Reply

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