如何在ruamel.yaml中保留换行格式实现无损往返更新?
解决ruamel.yaml往返更新时保留原换行格式的问题
要实现仅修改value字段,同时严格保留原YAML文件中description的多行折叠格式和url的单行长文本格式,需要调整ruamel.yaml的几个关键参数:
关键参数说明
keep_folded=True:强制保留原文件中用>标记的折叠块字符串的换行结构,避免被合并为单行。width=9999:设置足够大的行宽阈值,防止长URL文本被自动换行。preserve_quotes=True:保留原文件中字符串的引号格式(如果有),确保格式完全一致。
完整代码示例
from ruamel.yaml import YAML # 初始化YAML处理器,配置格式保留参数 yaml = YAML() yaml.keep_folded = True yaml.width = 9999 yaml.preserve_quotes = True # 加载原YAML文件 with open('input.yaml', 'r') as f: yaml_data = yaml.load(f) # 仅修改value字段 yaml_data['value'] = 'updated_value' # 写入更新后的文件,保留原格式 with open('output.yaml', 'w') as f: yaml.dump(yaml_data, f)
示例对比
原输入文件(input.yaml)
description: > This is a long description that spans multiple lines in the original file url: https://example.com/very/long/url/that/should/not/be/wrapped/even/though/it/is/extremely/long/and/goes/on/for/quite/a/while value: old_value
默认设置下的错误输出
description: This is a long description that spans multiple lines in the original file url: https://example.com/very/long/url/that/should/not/be/wrapped/even/though/it/is/ extremely/long/and/goes/on/for/quite/a/while value: updated_value
设置width=999后的错误输出
description: This is a long description that spans multiple lines in the original file url: https://example.com/very/long/url/that/should/not/be/wrapped/even/though/it/is/extremely/long/and/goes/on/for/quite/a/while value: updated_value
期望输出(配置正确后得到)
description: > This is a long description that spans multiple lines in the original file url: https://example.com/very/long/url/that/should/not/be/wrapped/even/though/it/is/extremely/long/and/goes/on/for/quite/a/while value: updated_value
内容的提问来源于stack exchange,提问作者crdavis
相关产品推荐
相关产品推荐

