You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用ruamel.yaml更新YAML时如何保留原有格式与注释不变

解决方法
  • 问题根源:ruamel.yaml默认配置下不会保留原始字符串的引号类型和换行格式,同时默认行宽较小,长字符串会被自动转义、折行,导致原有格式被破坏。
  • 核心解决方案:初始化YAML实例时调整配置,必要时手动指定字符串输出格式。

修改后可用代码

from ruamel.yaml import YAML

yaml = YAML()
# 开启保留原有引号类型
yaml.preserve_quotes = True
# 调大行宽到足够大,避免长字符串被强制折行生成转义字符
yaml.width = 4096
# 可选:匹配原有缩进格式,可根据你的文件实际缩进调整参数
yaml.indent(mapping=2, sequence=4, offset=2)

with open('test.yaml', encoding='utf-8') as f:
    test = yaml.load(f)

# 更新指定字段
test['sso']['version'] = '1.0.1'

with open('test2.yaml', 'w', encoding='utf-8') as f:
    yaml.dump(test, f)

如果上述配置后多行字符串格式仍有问题,可以手动强制指定字符串的输出格式:

from ruamel.yaml import YAML
from ruamel.yaml.scalarstring import SingleQuotedScalarString

yaml = YAML()
yaml.preserve_quotes = True
yaml.width = 4096

with open('test.yaml', encoding='utf-8') as f:
    test = yaml.load(f)

test['sso']['version'] = '1.0.1'
# 强制fileContent保持单引号多行格式输出
test['sso']['configs'][0]['fileContent'] = SingleQuotedScalarString(test['sso']['configs'][0]['fileContent'])

with open('test2.yaml', 'w', encoding='utf-8') as f:
    yaml.dump(test, f)

内容的提问来源于stack exchange,提问作者hoodakaushal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 11:18:00