How to remove 2 spaces from the output of ruamel.yaml dump?

后端 未结 1 1736
北荒
北荒 2021-01-21 18:49

With the help of yaml.indent(sequence=4, offset=2) the output is correct but there is extra space coming in each line and I know it is due to above indent function. Is

相关标签:
1条回答
  • 2021-01-21 18:55

    It is not so much the indent, as well as the offset of the sequence item indicator. This offset is taken within the space before the item and if the root node is a list, this gives correct YAML, but it looks sub-optimal.

    I have been looking at fixing this, but have not come up with a good solution. Until I do you'll have to post-process your output, which can be easily done:

    import sys
    import ruamel.yaml
    
    data = [{'item': 'Food_eat', 'Food': {'foodNo': 42536216,'type': 'fruit','moreInfo': ['organic']}}]
    
    def strip_leading_double_space(stream):
        if stream.startswith("  "):
            stream = stream[2:]
        return stream.replace("\n  ", "\n")
        # you could also do that on a line by line basis
        # return "".join([s[2:] if s.startswith("  ") else s for s in stream.splitlines(True)])
    
    
    yaml = ruamel.yaml.YAML()
    yaml.indent(sequence=4, offset=2)
    print('# < to show alignment')
    yaml.dump(data, sys.stdout, transform=strip_leading_double_space)
    

    which gives:

    # < to show alignment
    - item: Food_eat
      Food:
        foodNo: 42536216
        type: fruit
        moreInfo:
          - organic
    

    Of course it would be more efficient if the extra start-of-line spaces would not be generated in the first place.

    0 讨论(0)
提交回复
热议问题