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

使用ruamel.yaml时如何避免YAML字段值自动添加引号?

问题:如何让ruamel.yaml输出不带引号的布尔值false?

原YAML文件(manifest.yml)

ip:
  modules:
    shutdown-manager:
      version: 0.5
      package:
        repo: github
        path: ~/path
        manager: no

原Python代码

import ruamel.yaml

yaml = ruamel.yaml.YAML()

with open('manifest.yml') as stream:
   documents = yaml.load(stream)
   en=(documents['ip']['modules']['shutdown-manager'])
   en.insert(1, 'enabled', 'false')
   print(en)


with open('manifest_new.yml', 'wb') as stream:
    yaml.dump(documents, stream)

当前输出(manifest_new.yml)

ip:
  modules:
    shutdown-manager:
      version: 0.5
      enabled: 'false'
      package:
        repo: github
        path: ~/path
        manager: no

期望输出

ip:
  modules:
    shutdown-manager:
      version: 0.5
      enabled: false
      package:
        repo: github
        path: ~/path
        manager: no

解决方案

问题出在你插入的是字符串类型的'false',ruamel.yaml会把字符串原样输出并添加引号做区分。要输出YAML原生的布尔值false,需要传入Python的布尔值False(首字母大写)。

修改代码中插入enabled的那一行:

# 原代码
en.insert(1, 'enabled', 'false')
# 修改后
en.insert(1, 'enabled', False)

ruamel.yaml会自动将Python的False映射为YAML的小写false,输出时不会添加引号。执行修改后的代码,生成的YAML文件就会符合预期。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 08:35:33