如何用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
相关产品推荐
相关产品推荐

