6 Steps To Modify A Yaml Object In Python

Pavol Kutaj
May 3, 2021

--

The aim of this how-to-guide🏁 is to create a memorable 6-step instruction for the modification of a YAML file. I am using oyaml · PyPI to work with YAML objects in Python to keep the order or yaml items identical before and after manipulations.

1. steps

  1. import oyaml as yaml
  2. access resource in read mode with open(<file>, rt, utf8) as <fileAlias>:
  3. create <object> by loading the existing YAML with <object> = yaml.load(<fileAlias>, Loader=yaml.Loader)
  4. modify <object> and close the block
  5. access resource in a write mode: with open(<file>, wt, utf8) as <fileAlias>:
  6. dump object back to <fileAlias>.write(yaml.dump(<object>)) and close the block

2. example

import oyaml as yaml                                                   
def enrichConfig(section, docIndexItem):
with open('index.yaml', mode='rt', encoding='utf-8') as indexFile:
indexObject = yaml.load(indexFile, Loader=yaml.Loader)
for indexSection in indexObject['sections']:
if (indexSection['name'] == section):
indexSection['articles'].append(docIndexItem)
with open('index.yaml', mode='wt', encoding='utf-8') as conf_updated:
conf_updated.write(yaml.dump(indexObject))

--

--

No responses yet