【发布时间】:2021-05-02 21:17:12
【问题描述】:
我有一个包含以下内容的 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 更新文件以通过保留 cmets 来获得所需的输出?
这是我目前所拥有的:
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)
【问题讨论】:
标签: python file yaml pyyaml ruamel.yaml