如何使用 Ruamel.yaml 在某些数据前添加一个空行
How can I add a blank line before some data using Ruamel.yaml
我似乎无法弄清楚如何使用 Ruamel.yaml 在数据之间添加一个空行。
假设我有数据:
---
a: 1
b: 2
我需要添加到此以便我将拥有:
---
a: 1
b: 2
c: 3
我了解空白行是作为 CommentToken 实现的:
Comment(comment=None,
items={'data': [None, None, CommentToken(value=u'\n\n'), None], 'b': [None, None, CommentToken(value=u'\n\n'), None]})
我不知道如何操纵该结构。
那个 Comment
对象不是来自您提供的输入,因为 data
不是您映射中的键,它应该是 a
:
import ruamel.yaml
yaml_strs = [
"""\
---
a: 1
b: 2
""",
"""\
---
a: 1
b: 2
c: 3
"""]
for yaml_str in yaml_strs:
data = ruamel.yaml.round_trip_load(yaml_str)
print(data.ca)
给出:
Comment(comment=None,
items={'a': [None, None, CommentToken(), None]})
Comment(comment=None,
items={'a': [None, None, CommentToken(), None], 'b': [None, None, CommentToken(), None]})
比较以上评论应该会让您知道要尝试什么:
import sys
import ruamel.yaml
yaml_str = """\
---
a: 1
b: 2
"""
data = ruamel.yaml.round_trip_load(yaml_str)
data['c'] = 3
ct = data.ca.items['a'][2]
data.ca.items['b'] = [None, None, ct, None]
ruamel.yaml.round_trip_dump(data, sys.stdout)
给出:
a: 1
b: 2
c: 3
CommentToken ct
也可以从头开始构建:
ct = ruamel.yaml.tokens.CommentToken('\n\n', ruamel.yaml.error.CommentMark(0), None)
原样,例如在 ruamel.yaml.comments.CommentedBase.yaml_set_start_comment()
完成。
CommentMark()
的0
参数是注释缩进多少,空行情况下不重要,但还是要提供。
我似乎无法弄清楚如何使用 Ruamel.yaml 在数据之间添加一个空行。
假设我有数据:
---
a: 1
b: 2
我需要添加到此以便我将拥有:
---
a: 1
b: 2
c: 3
我了解空白行是作为 CommentToken 实现的:
Comment(comment=None,
items={'data': [None, None, CommentToken(value=u'\n\n'), None], 'b': [None, None, CommentToken(value=u'\n\n'), None]})
我不知道如何操纵该结构。
那个 Comment
对象不是来自您提供的输入,因为 data
不是您映射中的键,它应该是 a
:
import ruamel.yaml
yaml_strs = [
"""\
---
a: 1
b: 2
""",
"""\
---
a: 1
b: 2
c: 3
"""]
for yaml_str in yaml_strs:
data = ruamel.yaml.round_trip_load(yaml_str)
print(data.ca)
给出:
Comment(comment=None,
items={'a': [None, None, CommentToken(), None]})
Comment(comment=None,
items={'a': [None, None, CommentToken(), None], 'b': [None, None, CommentToken(), None]})
比较以上评论应该会让您知道要尝试什么:
import sys
import ruamel.yaml
yaml_str = """\
---
a: 1
b: 2
"""
data = ruamel.yaml.round_trip_load(yaml_str)
data['c'] = 3
ct = data.ca.items['a'][2]
data.ca.items['b'] = [None, None, ct, None]
ruamel.yaml.round_trip_dump(data, sys.stdout)
给出:
a: 1
b: 2
c: 3
CommentToken ct
也可以从头开始构建:
ct = ruamel.yaml.tokens.CommentToken('\n\n', ruamel.yaml.error.CommentMark(0), None)
原样,例如在 ruamel.yaml.comments.CommentedBase.yaml_set_start_comment()
完成。
CommentMark()
的0
参数是注释缩进多少,空行情况下不重要,但还是要提供。