[英]ruamel.yaml dump lists without adding new line at the end
我尝试使用以下代码段将 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/15\n - 23.30.0.10/15\n - 50.73.11.0/16\n - 198.0.0.0/16'
最好像上面的代码一样使用Path()
实例,特别是如果您的 YAML 文档将包含非 ASCII 字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.