python yaml update preserving order and comments

前端 未结 2 739
南方客
南方客 2021-01-18 08:10

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
    Pare         


        
2条回答
  •  爱一瞬间的悲伤
    2021-01-18 08:40

    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.

提交回复
热议问题