gpt4 book ai didi

python-3.x - python yaml更新保留顺序和注释

转载 作者:行者123 更新时间:2023-12-04 19:29:01 28 4
gpt4 key购买 nike

我使用 python 在 Yaml 中插入一个键,但我想保留 yaml 中的顺序和注释

#This Key is used for identifying Parent tests
ParentTest:
test:
JOb1: myjob
name: testjob
arrive: yes

现在我使用下面的代码插入新 key
params['ParentTest']['test']['new_key']='new value'
yaml_output=yaml.dump(pipeline_params, default_flow_style=False)

如何保留确切的顺序和注释?

下面到达移动但我也想保留顺序和评论

输出是:
 ParentTest:
test:
arrive: yes
JOb1: myjob
name: testjob

最佳答案

pyyaml 不能保留评论,但 ruamel做。

尝试这个:

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-3.x - python yaml更新保留顺序和注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47382227/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com