Python, after save yaml file the formatting of a list elements is not proper

Question:

I’m new to Python so maybe my problem is trivial but I don’t know how to solve it. I need to prepare a small script to modify yaml files. The problem I’ve faced is that after saving the file the elements that were a list are shifted to the left in the output file.

Here is my dummy script:

import sys
import yaml

filename = sys.argv[1]

with open(filename, 'r') as f:
    # Load the YAML content
    data = yaml.safe_load(f)

# Here will be my logic

with open('newfile.yml', 'w') as f:
    # Write the modified YAML content back to the file
    yaml.dump(data, f, default_flow_style=False, sort_keys=False)

Right now it only loads the file and saves the result into another file, but saved result is different from the original file.

Here is an example of the original file:

my_config:
  object1:
    key1: value1
    list_elements:
      - path: 'file.xml'
        mount_point: /deployments/file.xml
      - path: 'another_file.yml'
        mount_point: /deployments/another_file.yml
    key3: value3

And here is a saved result:

my_config:
  object1:
    key1: value1
    list_elements:
    - path: 'file.xml'
      mount_point: /deployments/file.xml
    - path: 'another_file.yml'
      mount_point: /deployments/another_file.yml
    key3: value3

All entries from list_elements were shifted left, can anyone tell me why that happens and how to solve that problem? I will need to modify only specific parts of the file and don’t want to touch anything else.

I played with parameters from yaml.dump but didn’t find anything that could help me.

Answers:

It looks like the pyyaml library has an open issue on this – there even is a workaround mentioned:

class Dumper(yaml.Dumper):
    def increase_indent(self, flow=False, *args, **kwargs):
        return super().increase_indent(flow=flow, indentless=False)

print(yaml.dump(data, Dumper=Dumper))

https://github.com/yaml/pyyaml/issues/234

Answered By: pgrz
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.