[英]Convert text file into yaml using python
I am trying to write a python script for automating my CI/CD.我正在尝试编写一个 python 脚本来自动化我的 CI/CD。 I have a file with my service names and docker image tags as mentioned below.
我有一个包含我的服务名称和 docker 图像标签的文件,如下所述。
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?如何在 python 甚至 shell 中实现这一点?
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)
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. PS:请在任何即将出现的问题中分享您的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.