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



我尝试使用下面的代码片段将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)

它正确转储,但我得到一个新的行追加到列表的末尾

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

我不希望新行插入到文件的末尾。我该怎么做呢?

换行符是块样式序列元素的表示代码的一部分。因为有了那个代码不太了解上下文,当然也不知道如何表示最后要转储的元素在文档中,不输出最后一个换行符几乎是不可能的。

但是,.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()))

给了:

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

最好像上面的代码那样使用Path()实例,特别是如果您的YAML文档将包含非ascii字符。