我有一个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
:其中:
请注意,您的序列缩进需要至少比您的序列缩进大2 偏移(2个位置有空间容纳
-
+空间)输出在键
school2
之后有emtpy行,这就是 在解析过程中,这些与关联。可以将其移动到新关键点,但 这不是小事。如果您需要这样做(这对于语义来说并不重要) 然后看看我的答案 here相关问题 更多 >
编程相关推荐