python yaml更新保留顺序和注释

shi*_*455 8 yaml python-3.x

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

#This Key is used for identifying Parent tests
    ParentTest:
       test:
         JOb1: myjob
         name: testjob
         arrive: yes
Run Code Online (Sandbox Code Playgroud)

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

params['ParentTest']['test']['new_key']='new value'
yaml_output=yaml.dump(pipeline_params, default_flow_style=False)
Run Code Online (Sandbox Code Playgroud)

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

下面到达移动但我也想保留订单和评论

输出是:

 ParentTest:
       test:
         arrive: yes
         JOb1: myjob
         name: testjob
Run Code Online (Sandbox Code Playgroud)

Ant*_*hon 6

虽然 @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)
Run Code Online (Sandbox Code Playgroud)

这使:

#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
Run Code Online (Sandbox Code Playgroud)


tin*_*ita 5

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)
Run Code Online (Sandbox Code Playgroud)

键的顺序也将被保留。