python yaml更新保留顺序和注释

时间:2017-11-19 21:33:00

标签: python-3.x yaml

我使用python将密钥插入Yaml但是我想保留yaml中的顺序和注释

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

现在我使用下面的代码插入新密钥

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

2 个答案:

答案 0 :(得分:3)

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)

也会保留按键的顺序。

答案 1 :(得分:2)

尽管@tinita的答案有效,但它使用了旧的ruamel.yaml API和 这样可以减少对加载/转储的控制。即使这样,你 无法保留映射的不一致缩进:密钥 ParentTest缩进了四个位置,键test再缩进一个位置 三个,而键JOb1仅位于两个位置。您可以“仅”设置 所有映射的缩进相同(即它们的键),并且与 所有序列的缩进(即它们的元素),以及 有足够的空间,您可以将序列指示器(-)偏移 序列元素缩进。

在默认的往返模式下,ruamel.yaml保留键顺序,并且 另外,您可以保留引号,折叠和文字标量。

以稍微扩展的YAML输入为例:

import sys
import ruamel.yaml

yaml_str = """\
#This Key is used for identifying Parent tests
    ParentTest:
       test:
         JOb1:
           - my
           - job
        #   ^ four indent positions for the sequence elements
        # ^   two position offset for the sequence indicator '-'
         name: 'testjob'  # quotes added to show working of .preserve_quotes = True
         arrive: yes
"""

yaml = ruamel.yaml.YAML()
yaml.indent(mapping=4, sequence=4, offset=2)
yaml.preserve_quotes = True
params = yaml.load(yaml_str)
params['ParentTest']['test']['new_key'] = 'new value'
params['ParentTest']['test'].yaml_add_eol_comment('some comment', key='new_key', column=40) # column is optional
yaml.dump(params, sys.stdout)

给出:

#This Key is used for identifying Parent tests
ParentTest:
    test:
        JOb1:
          - my
          - job
        #   ^ four indent positions for the sequence elements
        # ^   two position offset for the sequence indicator '-'
        name: 'testjob'   # quotes added to show working of .preserve_quotes = True
        arrive: yes
        new_key: new value              # some comment