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

如何使用Ruamel在YAML列表项之间添加空行?

解决方案

要实现列表元素之间的空行效果,不能直接追加None或CommentToken,需利用ruamel.yaml的注释系统来控制空行输出,具体代码如下:

from ruamel.yaml import YAML
from pathlib import Path

yaml = YAML()
yaml.preserve_quotes = True
yaml.allow_duplicate_keys = True
formatted_yaml = yaml.load(Path(my_file).open().read())

for idx, item in enumerate(my_items):
    formatted_yaml.append(item)
    # 给非首个元素(含原文件已有元素后的第一个新元素)添加前置空行
    if idx > 0 or len(formatted_yaml) > 1:
        current_idx = len(formatted_yaml) - 1
        # 给当前元素的列表符号(-)前插入空行
        formatted_yaml.yaml_set_comment_before_after_key(current_idx, before='\n')

# 写入输出文件
with Path('output.yaml').open('w') as f:
    yaml.dump(formatted_yaml, f)

原理说明

  1. 直接追加None会被序列化为空列表项(- ),并非真正的空行;
  2. CommentToken是ruamel.yaml的内部解析令牌,不能作为列表元素直接添加,因此会抛出序列化错误;
  3. 利用CommentedSeq(yaml.load返回的列表类型)的yaml_set_comment_before_after_key方法,给目标元素设置before='\n',可在该元素的列表符号-前插入空行,完美匹配你要的输出格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 00:00:55