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

如何用Python yaml.dump(PyYAML)在列表块前后添加空行

给PyYAML输出的列表项添加空行的解决方案

针对长YAML文档列表可读性差的问题,可通过自定义PyYAML的Dumper类,在列表项之间插入空行,实现预期格式。

实现代码

import yaml
from yaml.events import SequenceItemEvent, SequenceStartEvent

class CustomDumper(yaml.Dumper):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._is_first_sequence_item = True

    def emit(self, event):
        if isinstance(event, SequenceStartEvent):
            self._is_first_sequence_item = True
        elif isinstance(event, SequenceItemEvent) and not self._is_first_sequence_item:
            self.write_line_break()
        elif isinstance(event, SequenceItemEvent):
            self._is_first_sequence_item = False
        
        super().emit(event)

# 示例数据
network_config = {
    'interfaces': [
        {
            'name': 'phy-1_1_1',
            'description': 'Ansible: cfg phy-1_1_1',
            'breakout': 'to-four'
        },
        {
            'name': 'phy-1_1_2',
            'description': 'Interface phy-1_1_2',
            'admin_status': 'down'
        },
        {
            'name': 'phy-1_1_3',
            'description': 'Interface phy-1_1_3',
            'admin_status': 'down'
        }
    ]
}

# 生成带空行的YAML输出
print(yaml.dump(
    network_config,
    Dumper=CustomDumper,
    default_flow_style=False,
    indent=2,
    sort_keys=False
))

代码说明

  • 自定义CustomDumper继承PyYAML原生Dumper,通过状态标记跟踪序列元素位置
  • 遇到序列开始事件时,重置"是否为第一个元素"的标记
  • 处理非第一个序列项时,额外写入一行空行,实现列表项之间的分隔
  • 保留原生Dumper的其他功能,确保YAML格式正确性

输出效果

interfaces:
  - name: phy-1_1_1
    description: Ansible: cfg phy-1_1_1
    breakout: to-four

  - name: phy-1_1_2
    description: Interface phy-1_1_2
    admin_status: down

  - name: phy-1_1_3
    description: Interface phy-1_1_3
    admin_status: down

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 18:36:25