![](/img/trans.png)
[英]How do I edit a YAML file through python using ruamel.yaml and not pyyaml?
[英]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 通过保留注释来更新文件以获得所需的 output?
这是我到目前为止所拥有的:
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 留出空间)
output 在键school2
之后有空行,因为这是在解析过程中与之关联的内容。 这可以移动到新密钥,但这不是微不足道的。 如果您需要这样做(这对 YAML 文档的语义并不重要),请在此处查看我的回答
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.