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

如何使用python和ruamel更新此yaml文件?,python,file,yaml,pyyaml,ruamel.yaml,Python,File,Yaml,Pyyaml,Ruamel.yaml,我有一个test.yaml文件,其中包含以下内容: school_ids: school1: "001" #important school2 school2: "002" targets: neighborhood1: schools: - school1-paloalto teachers: - 33 neighborhood2: schools: - school2

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

您只是在转储从头创建的
新目标
,而不是使用
代码
甚至
目标
。 相反,您应该使用该
code
that 加载并扩展与其根级别键关联的值,然后转储
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行,这就是 在解析过程中,这些与关联。可以将其移动到新关键点,但 这不是小事。如果您需要这样做(这对于语义来说并不重要) 然后看看我的答案

感谢您的友好和及时回复@Anthon。我注意到,在我下面的示例中,您的回答中也提到了,我们正在sys.stdout中打印。是否有方法更新同一文件并将更新的字段和值写入其中?使用相同的ruamel模块。正在更新文件。。。提前谢谢你@贝克:如果您使用的是
pathlib.Path
实例(和我一样),那么写回文件就像执行
yaml.dump(code,inp)
一样简单。适当的操作将为您打开和关闭文件。如果输出应该转到不同的文件(或者如果需要保存旧的文件内容,请考虑重命名<代码> Inp< /Cord>),请新建一个<代码>路径>代码>