问题
I can't seem to figure out how I can add a blank line between data using Ruamel.yaml.
Suppose I have data:
---
a: 1
b: 2
I need to add to this so that I will have:
---
a: 1
b: 2
c: 3
I understand that the blank line is implemented as a CommentToken:
Comment(comment=None,
items={'data': [None, None, CommentToken(value=u'\n\n'), None], 'b': [None, None, CommentToken(value=u'\n\n'), None]})
What I don't know is how to manipulate that structure.
回答1:
That Comment
object is not from the input that you give, as data
is not a key in your mapping, that should be 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)
gives:
Comment(comment=None,
items={'a': [None, None, CommentToken(), None]})
Comment(comment=None,
items={'a': [None, None, CommentToken(), None], 'b': [None, None, CommentToken(), None]})
comparing the above comments should give you an idea of what to try:
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)
which gives:
a: 1
b: 2
c: 3
The CommentToken ct
can also be constructed from scratch:
ct = ruamel.yaml.tokens.CommentToken('\n\n', ruamel.yaml.error.CommentMark(0), None)
as is, e.g. done in ruamel.yaml.comments.CommentedBase.yaml_set_start_comment()
.
The 0
parameter to CommentMark()
is how far the comment is indented, which is not important in case of empty lines, but still needs to be provided.
来源:https://stackoverflow.com/questions/42198379/how-can-i-add-a-blank-line-before-some-data-using-ruamel-yaml