[英]How do I update this yaml file with python and ruamel?
I have a test.yaml file with content:我有一个包含以下内容的 test.yaml 文件:
school_ids:
school1: "001"
#important school2
school2: "002"
targets:
neighborhood1:
schools:
- school1-paloalto
teachers:
- 33
neighborhood2:
schools:
- school2-paloalto
teachers:
- 35
I want to use ruamel to update the file to look like this:我想使用 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
How do I use ruamel to update the file to get the desired output by preserving the comments?如何使用 ruamel 通过保留注释来更新文件以获得所需的 output?
Here's what I have so far:这是我到目前为止所拥有的:
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)
You are just dumping new_target
which you create from scratch not using the code
or even targets
.您只是在转储您从头开始创建的
new_target
,而不是使用code
甚至targets
。 Instead you should either use that code
that you loaded and extend the values associated with its root level keys and then dump code
:相反,您应该使用您加载的
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)
which gives:这使:
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'
Please note that your sequence indent needs to be at least 2 greater than your offset (2 positions to have room for -
+ SPACE)请注意,您的序列缩进需要至少比您的偏移量大 2(2 个位置为
-
+ SPACE 留出空间)
The output has the emtpy lines between after the key school2
, as that is what these are associated with during parsing. output 在键
school2
之后有空行,因为这是在解析过程中与之关联的内容。 This can be moved to the new key, but it is not trivial.这可以移动到新密钥,但这不是微不足道的。 If you need to do that (it is not important for the semantics of the YAML document), then have a look at my answer here
如果您需要这样做(这对 YAML 文档的语义并不重要),请在此处查看我的回答
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.