简体   繁体   English

ruamel.yaml 转储列表而不在末尾添加新行

[英]ruamel.yaml dump lists without adding new line at the end

I trying to dump a dict object as YAML using the snippet below:我尝试使用以下代码段将 dict 对象转储为 YAML:

from ruamel.yaml import YAML
# YAML settings
yaml = YAML(typ="rt")
yaml.default_flow_style = False
yaml.explicit_start = False
yaml.indent(mapping=2, sequence=4, offset=2)

rip= {"rip_routes": ["23.24.10.0/15", "23.30.0.10/15", "50.73.11.0/16", "198.0.0.0/16"]}

file = 'test.yaml'
with open(file, "w") as f:
    yaml.dump(rip, f)

It dumps correctly, but I am getting an new line appended to the end of the list它正确转储,但我在列表末尾添加了一个新行

   rip_routes:
      - 23.24.10.0/15
      - 23.30.0.10/15
      - 198.0.11.0/16

I don't want the new line to be inserted at the end of file.我不希望在文件末尾插入新行。 How can I do it?我该怎么做?

The newline is part of the representation code for block style sequence elements.换行符是块样式序列元素表示代码的一部分。 And since that code doesn't have much knowledge about context, and certainly not about representing the last element to be dumped in a document, it is almost impossible for the final newline not to be output.而且由于该代码对上下文没有太多了解,当然也没有关于表示要转储到文档中的最后一个元素的知识,因此几乎不可能不输出最后的换行符。

However, the .dump() method has an optional transform parameter that allows you to run the output of the dumped text through some filter:但是, .dump()方法有一个可选的transform参数,允许您通过一些过滤器运行转储文本的输出:

import sys
import pathlib
import string
import ruamel.yaml

# YAML settings
yaml = ruamel.yaml.YAML(typ="rt")
yaml.default_flow_style = False
yaml.explicit_start = False
yaml.indent(mapping=2, sequence=4, offset=2)

rip= {"rip_routes": ["23.24.10.0/15", "23.30.0.10/15", "50.73.11.0/16", "198.0.0.0/16"]}

def strip_final_newline(s):
    if not s or s[-1] != '\n':
        return s
    return s[:-1]

file = pathlib.Path('test.yaml')
yaml.dump(rip, file, transform=strip_final_newline)

print(repr(file.read_text()))

which gives:这使:

'rip_routes:\n  - 23.24.10.0/15\n  - 23.30.0.10/15\n  - 50.73.11.0/16\n  - 198.0.0.0/16'

It is better to use Path() instances as in the code above, especially if your YAML document is going to contain non-ASCII characters.最好像上面的代码一样使用Path()实例,特别是如果您的 YAML 文档将包含非 ASCII 字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM