Modify/Update YAML Files Using Python 3 & ruamel.yaml

If you want to preserve the order of your mapping keys, the white space between the elements of the root-level sequence, and the comment, e.g. because this file is under revision control, then I would highly suggest you use ruamel.yaml

pip install ruamel.yaml

Write your YAML code in a file called input.yaml. We are using this file inside our code.

import sys
import ruamel.yaml

yaml = ruamel.yaml.YAML()
# yaml.preserve_quotes = True
with open('input.yaml') as fp:
    data = yaml.load(fp)
for elem in data:
    if elem['name'] == 'sense2':
         elem['value'] = 1234
         break  # no need to iterate further
yaml.dump(data, sys.stdout)

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.