首页 > 解决方案 > Python ruamel 不保留 yaml 中换行符的格式

问题描述

我的原始 yaml 文件在我转储后要保留的破折号 (-) 后包含换行符

#  This is my yaml
color_1:
    blue: 
        -
# I want to preserve this newline after the dash
            width_1: "1"
            height_1: [1]
            size_1: 4
        -
            width_1: "2"
            height_2: [1,2,3,4]
            size_2: 4

我的代码

import sys
from ruamel.yaml import YAML
yaml = YAML()
yaml.preserve_quotes = True
yaml.boolean_representation = ['False', 'True']
yaml.indent(mapping=4, sequence=3, offset=0)

def main():
    config_path = "my_yaml_before.yaml"
    config = yaml.load(open(config_path))
    yaml.dump(config, sys.stdout)

if __name__ == "__main__":
    main()

在我运行我的脚本后,我看到了如下删除换行符的转储文件,我还注意到在列表的项目之间有额外的空间,我也不想得到

#  This is my yaml
color_1:
    blue:
# I want to preserve this newline after the dash
    -  width_1: "1"
       height_1: [1]
       size_1: 4
    -  width_1: "2"
       height_2: [1, 2, 3, 4]
       size_2: 4

标签: pythonyamlnewlineindentationruamel.yaml

解决方案


推荐阅读