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

2024-06-25 23:27:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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)

Tags: 文件idsyamlsyscoderuameltargetsschool
1条回答
网友
1楼 · 发布于 2024-06-25 23:27:21

您只是在转储从头创建的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个位置有空间容纳-+空间)

输出在键school2之后有emtpy行,这就是 在解析过程中,这些与关联。可以将其移动到新关键点,但 这不是小事。如果您需要这样做(这对于语义来说并不重要) 然后看看我的答案 here

相关问题 更多 >