I have a problem with dumping data back to YAML with correct format. Looked into other similar questions but didn't find solution for this problem. Current code in Python:
template = yaml.load(open(templateFile), Loader=yaml.RoundTripLoader)
template["key"] = new_value
yaml.dump(template, sys.stdout, Dumper=yaml.RoundTripDumper, indent=2)
Input:
parameters:
key: value
Output:
parameters:
key: value
key: new_value
Expected output:
parameters:
key: new_value
How should the code be modified, to either change the old "key" value, or enter a new one with correct indenting?
You'll have to assign the new_value
to the right mapping/dict:
import sys
from ruamel import yaml
template_file = 'input.yaml'
new_value = 'new_value'
template = yaml.load(open(template_file), Loader=yaml.RoundTripLoader)
template['parameters']['key'] = new_value
yaml.dump(template, sys.stdout, Dumper=yaml.RoundTripDumper, indent=2)
a new value indented "under" key
would require:
template['parameters']['newkey'] = 'added_value'
please note that it is customary to use snake_case for Python variables like template_file
(RoundTripLoader
/RoundTripDumper
are the names of classes)