如何使用ruamel.yaml在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:
CommentedSeqreplaces 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_keymethod 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

