python yaml更新保留顺序和注释 [英] python yaml update preserving order and comments
本文介绍了python yaml更新保留顺序和注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 python 在 Yaml 中插入一个密钥,但我想保留 yaml 中的顺序和注释
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
输出是:
ParentTest:
test:
arrive: yes
JOb1: myjob
name: testjob
推荐答案
pyyaml 不能保留评论,但是 ruamel 确实如此.
pyyaml cannot keep comments, but ruamel does.
试试这个:
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)
键的顺序也将保留.
这篇关于python yaml更新保留顺序和注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文