简体   繁体   中英

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

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 there any way to remove the 2 extra spaces from each line(I don't wont to use strip()).

Code:

import sys
import ruamel.yaml

data = [{'item': 'Food_eat', 'Food': {'foodNo': 42536216,'type': 'fruit','moreInfo': ['organic']}}]

yaml = ruamel.yaml.YAML()
yaml.indent(sequence=4, offset=2)
yaml.dump(data, sys.stdout)

Output of above code:

  - item: Food_eat
    Food:
      foodNo: 42536216
      type: fruit
      moreInfo:
        - organic

Required output:

- item: Food_eat
  Food:
    foodNo: 42536216
    type: fruit
    moreInfo:
      - organic

PS: I have taken help from this stackoverflow question by me: How to safe_dump the dictionary and list into YAML?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM