[Python] Modifying YAML using ruamel.yaml adds extra new lines

Discussão em 'Python' iniciado por Stack, Março 25, 2025.

  1. Stack

    Stack Membro Participativo

    I need to add an extra value to an existing key in a YAML file. Following is the code I'm using.

    with open(yaml_in_path, 'r') as f:
    doc, ind, bsi = load_yaml_guess_indent(f, preserve_quotes=True)
    doc['phase1'] += ['c']
    with open(yaml_out_path, 'w') as f:
    ruamel.yaml.round_trip_dump(doc, f,
    indent=2, block_seq_indent=bsi)


    This is the input and output.

    Input

    phase1:
    - a
    # a comment.
    - b

    phase2:
    - d


    Output

    phase1:
    - a
    # a comment.
    - b

    - c
    phase2:
    - d


    How can I get rid of the new line between b and c? (This problem is not there when phase1 is the only key in the file or when there are no blank lines between phase1 and phase2.)

    Continue reading...

Compartilhe esta Página