ruamel.yaml往返序列化时如何保留多行原始字符串格式?
解决办法
ruamel.yaml的往返模式默认会将双引号内的多行字符串转换为带反斜杠的折叠格式,可通过以下方式解决:
设置超大宽度阈值
初始化YAML对象后添加yaml.width = float("inf")(或远大于字符串长度的数值),避免ruamel.yaml因字符串过长自动拆分换行,从而保留原始多行结构:yaml = ruamel.yaml.YAML() # 默认往返模式 yaml.allow_duplicate_keys = True yaml.preserve_quotes = True yaml.explicit_start = True yaml.width = float("inf") # 添加此配置手动保留ScalarString类型
ruamel.yaml会将双引号字符串解析为DoubleQuotedScalarString类型,若需修改内容,务必用ruamel.yaml.scalarstring.DoubleQuotedScalarString重新包装,避免格式丢失:from ruamel.yaml.scalarstring import DoubleQuotedScalarString # 修改字符串时保持格式 data['test']['long'] = DoubleQuotedScalarString("Modified text\n across two lines.")备选:改用块样式字符串
若无需严格保留双引号格式,可将原始字符串改为块样式(|或>),这种格式在往返模式下更易被完整保留:test: long: | This is a sample text across two lines.
内容的提问来源于stack exchange,提问作者thebenman
相关产品推荐
相关产品推荐

