如何使用 python 和 ruamel 更新此 yaml 文件?

How do I update this yaml file with python and ruamel?

我有一个 test.yaml 文件,内容为:

school_ids:
  school1: "001"

  #important school2
  school2: "002"


targets:
  neighborhood1:
    schools:
      - school1-paloalto
    teachers:
      - 33
  neighborhood2:
    schools:
      - school2-paloalto
    teachers:
      - 35

我想使用 ruamel 将文件更新为如下所示:

school_ids:
  school1: "001"

  #important school2
  school2: "002"

  school3: "003"


targets:
  neighborhood1:
    schools:
      - school1-paloalto
    teachers:
      - 33
  neighborhood2:
    schools:
      - school2-paloalto
    teachers:
      - 35
  neighborhood3:
    schools:
      - school3-paloalto
    teachers:
      - 31

如何使用 ruamel 更新文件以通过保留注释获得所需的输出?

这是我目前的情况:

import sys
from ruamel.yaml import YAML

inp = open('/targets.yaml', 'r').read()

yaml = YAML()

code = yaml.load(inp)
account_ids = code['school_ids']
account_ids['new_school'] = "003"
#yaml.dump(account_ids, sys.stdout)


targets = code['targets']
new_target = dict(neighborhood3=dict(schools=["school3-paloalto"], teachers=["31"]))
yaml = YAML()
yaml.indent(mapping=2, sequence=3, offset=2)
yaml.dump(new_target, sys.stdout)

您只是在转储您从头开始创建的 new_target,而不是使用 code 甚至 targets。 相反,您应该使用那个 code 您加载并扩展了与其根级键关联的值,然后转储 code:

import sys
from pathlib import Path
from ruamel.yaml import YAML

inp = Path('test.yaml')

yaml = YAML()

code = yaml.load(inp)
school_ids = code['school_ids']
school_ids['school3'] = "003"


targets = code['targets']
targets['neighborhood3'] = dict(schools=["school3-paloalto"], teachers=["31"])
yaml = YAML()
yaml.indent(mapping=2, sequence=4, offset=2)
yaml.dump(code, sys.stdout)

给出:

school_ids:
  school1: '001'

  #important school2
  school2: '002'


  school3: '003'
targets:
  neighborhood1:
    schools:
      - school1-paloalto
    teachers:
      - 33
  neighborhood2:
    schools:
      - school2-paloalto
    teachers:
      - 35
  neighborhood3:
    schools:
      - school3-paloalto
    teachers:
      - '31'

请注意,您的序列缩进需要至少比您的缩进大 2 偏移量(2 个位置有 - + SPACE 的空间)

输出在键 school2 之后有空行,因为那是什么 这些与解析期间相关联。这可以移动到新密钥,但是 这不是微不足道的。如果你需要这样做(这对语义并不重要 YAML 文件),然后看看我的回答