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

如何使用ruamel.yaml在YAML文件的序列元素间插入空行?

How to Insert Blank Lines Between List Items When Generating YAML with ruamel.yaml?

Question:

I'm using the ruamel.yaml library to generate YAML files. Here's my current code:

from ruamel.yaml import YAML
yaml = YAML()
user = [{"login":"login1","fullName":"First1 Last1", "list":["a"]},{"login":"login2","fullName":"First2 Last2", "list":["b"]}]
test = {"category":[{"year":2023,"users":user}]}
yaml.indent(mapping=4, sequence=4, offset=2)
yaml.width = 2048
with open(r'test.yml', 'w') as file:
    documents = yaml.dump(test, file)

After running this code, the generated test.yml looks like this:

category:
    - year: 2023
      users:
        - login: login1
          fullName: First1 Last1
          list:
            - a
        - login: login2
          fullName: First2 Last2
          list:
            - b

I need to insert a blank line between the two user entries under the users list. My desired output is:

category:
    - year: 2023
      users:
        - login: login1
          fullName: First1 Last1
          list:
            - a

        - login: login2
          fullName: First2 Last2
          list:
            - b

How can I modify my code to achieve this?

Answer:

To add that blank line between your user entries, you'll need to use ruamel.yaml's CommentedSeq type (it's built for sequences that need comment or whitespace control) and use the yaml_set_comment_before_after_key method to insert a newline before the second list item.

Here's the modified code:

from ruamel.yaml import YAML, CommentedSeq

yaml = YAML()
# Convert the regular list to a CommentedSeq so we can control whitespace
user = CommentedSeq([
    {"login": "login1", "fullName": "First1 Last1", "list": ["a"]},
    {"login": "login2", "fullName": "First2 Last2", "list": ["b"]}
])
# Insert a newline before the second element (index 1) to create a blank line
user.yaml_set_comment_before_after_key(1, before='\n')

test = {"category": [{"year": 2023, "users": user}]}
yaml.indent(mapping=4, sequence=4, offset=2)
yaml.width = 2048
with open(r'test.yml', 'w') as file:
    yaml.dump(test, file)

Quick breakdown:

  • CommentedSeq replaces the regular Python list because it gives you fine-grained control over how the sequence is serialized, including adding blank lines between elements.
  • The yaml_set_comment_before_after_key method targets the element at index 1 (your second user entry) and adds a newline before it. That newline translates directly to the blank line you want in the final YAML.

When you run this code, your test.yml will have the blank line between the two user entries exactly as you expected.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 15:07:33