从 YAML 中读取、编辑并写入
加载的 YAML 可以使用 .as_yaml() 修改并再次转储,同时保留注释。
请注意,由于 StrictYAML 底层的库 (ruamel.yaml) 中存在一些错误,虽然解析的数据应该完全相同,但确切的语法(换行符、注释位置等)可能不完全相同。
示例 yaml_snippet
# Some comment
a: â # value comment
# Another comment
b:
x: 4
y: 5
c:
- a: 1
- b: 2
from strictyaml import Map, MapPattern, EmptyDict, Str, Seq, Int, load
from ensure import Ensure
schema = Map({
"a": Str(),
"b": Map({"x": Int(), "y": Int()}),
"c": EmptyDict() | Seq(MapPattern(Str(), Str())),
})
已注释
Ensure(load(yaml_snippet, schema).as_yaml()).equals(yaml_snippet)
使用无效变量修改
to_modify = load(yaml_snippet, schema)
to_modify['b']['x'] = 2
to_modify['c'][0]['a'] = '3'
to_modify['b']['x'] = 'not an integer'
strictyaml.exceptions.YAMLSerializationError:
'not an integer' not an integer.
使用浮点数修改
to_modify = load(yaml_snippet, schema)
to_modify['c'][0]['a'] = "1.0001"
print(to_modify.as_yaml())
# Some comment
a: â # value comment
# Another comment
b:
x: 4
y: 5
c:
- a: 1.0001
- b: 2
修改多行字符串
a: some
b: |
text
schema = Map({"a": Str(), "b": Str()})
to_modify = load(yaml_snippet, schema)
to_modify['a'] = 'changed'
print(to_modify.as_yaml())
a: changed
b: |
text
使用一个变量修改
to_modify = load(yaml_snippet, schema)
to_modify['b']['x'] = 2
to_modify['c'][0]['a'] = '3'
print(to_modify.as_yaml())
# Some comment
a: â # value comment
# Another comment
b:
x: 2
y: 5
c:
- a: 3
- b: 2
跨行的文本
to_modify = load(yaml_snippet, schema)
to_modify['c'][0]['a'] = "text\nacross\nlines"
print(to_modify.as_yaml())
# Some comment
a: â # value comment
# Another comment
b:
x: 4
y: 5
c:
- a: |-
text
across
lines
- b: 2
带空字典
to_modify = load(yaml_snippet, schema)
to_modify['c'] = {}
print(to_modify.as_yaml())
# Some comment
a: â # value comment
# Another comment
b:
x: 4
y: 5
c: