How to combine YAML files in python?

Viewed 632

I got some Kubernetes YAML files which I need to combine.

For that, I tried using Python.

The second file, sample.yaml, should be merged to the first file, source.yaml.

The source.yaml file has one section sample:, where the complete sample.yaml should be added.

I tried using the below code:

#pip install pyyaml
import yaml

def yaml_loader(filepath):
    #Loads a yaml file
    with open(filepath,'r')as file_descriptor:
        data = yaml.load(file_descriptor)
    return data

def yaml_dump(filepath,data):
    with open(filepath,"w") as file_descriptor:
        yaml.dump(data, file_descriptor)


if __name__ == "__main__":
    file_path1 = "source"
    data1 = yaml_loader(file_path1)
    file_path2 = "sample.yaml"

    with open(file_path2, 'r') as file2:
        sample_yaml = file2.read()
    data1['data']['sample'] = sample_yml
    yaml_dump("temp.yml", data1)

This is creating a new file temp.yml but instead of line breaks, it is saving \n as strings:

How to fix this?

1 Answers

Your original YAML may have issues. If you use VS Code, format your YAML file. Click on the bottom of vscode(if using the same) [Spaces]

enter image description here

and select convert indentation to spaces

enter image description here

also, you can check if YAML module has any indentation property to be configured ,when loading the file

Related