【发布时间】:2020-11-24 18:13:09
【问题描述】:
我正在使用 ruamel.yaml 包,我似乎无法让它以格式良好的流样式输出。我想通过尾随逗号和换行符将元素保持在同一级别。我也想保留每一条评论,转换为流式风格后似乎有些消失了。这是一个例子:
原创
background_opacity: 0.9 # comment
cursor: {style: Beam}
# comment
font:
normal: {family: Fira Code, style: Retina} # comment
size: 12.0 # comment
打算
{
background_opacity: 0.9, # comment
cursor: {style: Beam},
# comment
font: {
normal: {family: Fira Code, style: Retina}, # comment
size: 12.0 # comment
}
}
实际
{background_opacity: 0.9 # comment
, cursor: {style: Beam}, font: {normal: {family: Fira Code, style: Retina} # comment
, size: 12.0 # comment
}}
我的代码附在下面。我对 YAML 和 ruamel.yaml 还很陌生,所以对于任何简单的错误,我深表歉意。
from ruamel.yaml import YAML
def round_trip(sout, sin, idt):
yaml = YAML()
assert idt >= 2
yaml.indent(mapping=idt, sequence=idt, offset=idt-2)
yaml.preserve_quotes = True
data = yaml.load(sin)
if data is not None:
data.fa.set_flow_style() # needs fixing: commas are not trailing
yaml.dump(data, sout)
else:
print("the file is empty") # needs fixing: should dump original file
【问题讨论】:
标签: python yaml ruamel.yaml