Home > Back-end >  Convert text file into yaml using python
Convert text file into yaml using python

Time:09-27

I am trying to write a python script for automating my CI/CD. I have a file with my service names and docker image tags as mentioned below.

service1:d7e5d468
service2:g7e5d468
service3:h629hg09
nginx:y5227hg89
tomcat:bc1571hg189

Now I need it in the below format for my automation to work.

service1:
  image:
    tag: d7e5d468
service2:
  image:
    tag: g7e5d468 

How can I achieve this in python or even shell?

CodePudding user response:

Does this answer your question ?

lines = []
with open('file.txt', 'r') as f:
    while line := f.readline():
        lines  = [line.rstrip().split(':')]
yaml_format = yaml.dump(
    {service: {
        'image': {
            'tag': name
        }
    }
     for service, name in lines})
with open('result.yaml', 'w') as f:
    f.write(yaml_format)

CodePudding user response:

There are multiple ways to do this, an easy one is as follows :

import yaml

dictionary = {}
with open("file.txt", "r") as f:
    for line in f:
        dictionary[line.split(":")[0]] = {"image": {"tag": line.split(":")[1].strip()}}
    f.close()

with open("newFile.yml", "w") as f:
    yaml.dump(dictionary, f, default_flow_style=False)
    f.close()

PS : Please share your code in any upcoming questions.

  • Related