6 Steps To Modify A Yaml Object In Python
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
import oyaml as yaml
- access resource in read mode
with open(<file>, rt, utf8) as <fileAlias>:
- create
<object>
by loading the existing YAML with<object> = yaml.load(<fileAlias>, Loader=yaml.Loader)
- modify
<object>
and close the block - access resource in a write mode:
with open(<file>, wt, utf8) as <fileAlias>:
- 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))