Im inserting a key into Yaml using python but I would like to preserve order and comments in the yaml
#This Key is used for identifying Parent tests
ParentTest:
test:
JOb1: myjob
name: testjob
arrive: yes
Now Im using below code to insert new key
params['ParentTest']['test']['new_key']='new value'
yaml_output=yaml.dump(pipeline_params, default_flow_style=False)
How to preserve the exact order and comments ?
Below arrive moved up but I want to preserve order & comments as well
output is :
ParentTest:
test:
arrive: yes
JOb1: myjob
name: testjob
I've found in a StackOverflow question, and a pyyaml PR that the yaml spec does not guarantee an order of keys in a mapping. I found in the PyYAML PR that it automatically sorts the keys when you run . dump() , so the YAML file itself is already in a different order.
In order to add comments to a YAML file, you simply have to use the # (hashtag symbol) at the start of the line.
Loading a YAML Document Safely Using safe_load() safe_load(stream) Parses the given and returns a Python object constructed from the first document in the stream. safe_load recognizes only standard YAML tags and cannot construct an arbitrary Python object.
What does greater than mean in YAML? The greater than sign notation, also referred to as “folded block”: folded: > This block of text will be the value of 'folded', but this. time, all newlines will be replaced with a single space. Blank lines, like above, are converted to a newline character.
pyyaml cannot keep comments, but ruamel does.
Try this:
doc = ruamel.yaml.load(yaml, Loader=ruamel.yaml.RoundTripLoader)
doc['ParentTest']['test']['new_key'] = 'new value'
print ruamel.yaml.dump(doc, Dumper=ruamel.yaml.RoundTripDumper)
The order of keys will also be preserved.
Edit: Look at Anthon's answer from 2020: https://stackoverflow.com/a/59659659/93745
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With