[英]Convert text file into yaml using python
我正在嘗試編寫一個 python 腳本來自動化我的 CI/CD。 我有一個包含我的服務名稱和 docker 圖像標簽的文件,如下所述。
service1:d7e5d468
service2:g7e5d468
service3:h629hg09
nginx:y5227hg89
tomcat:bc1571hg189
現在我需要以下格式的它才能使我的自動化工作。
service1:
image:
tag: d7e5d468
service2:
image:
tag: g7e5d468
如何在 python 甚至 shell 中實現這一點?
這回答了你的問題了嗎?
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)
有多種方法可以做到這一點,一種簡單的方法如下:
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:請在任何即將出現的問題中分享您的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.