如何使用Ruamel.yaml在某些数据之前添加空白行 [英] How can I add a blank line before some data using Ruamel.yaml

查看:417
本文介绍了如何使用Ruamel.yaml在某些数据之前添加空白行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法弄清楚如何使用Ruamel.yaml在数据之间添加空白行.

I can't seem to figure out how I can add a blank line between data using Ruamel.yaml.

假设我有数据:

---
a: 1

b: 2

我需要添加到此内容中,以便:

I need to add to this so that I will have:

---
a: 1

b: 2

c: 3

我知道空白行是作为CommentToken实现的:

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.

推荐答案

Comment对象不是来自您提供的输入,因为data不是映射中的键,应为a:

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)

给予:

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)

给出:

a: 1

b: 2

c: 3

CommentToken ct也可以从头开始构建:

The CommentToken ct can also be constructed from scratch:

ct = ruamel.yaml.tokens.CommentToken('\n\n', ruamel.yaml.error.CommentMark(0), None)

原样,例如在ruamel.yaml.comments.CommentedBase.yaml_set_start_comment()中完成.

as is, e.g. done in ruamel.yaml.comments.CommentedBase.yaml_set_start_comment().

CommentMark()0参数是注释缩进的距离,在空行的情况下这并不重要,但仍需要提供.

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.

这篇关于如何使用Ruamel.yaml在某些数据之前添加空白行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆