从文本文件创建YAML文件

问题描述 投票:0回答:1

我是python和脚本新手。我的hostname.txt文件包含以下内容:

1.1.1.1
2.2.2.2
3.3.3.3

想要在hostname.yaml文件中使用以下格式,最好使用python(bash shell也可以)。

host1:
  hostname: 1.1.1.1
  platform: linux

host2:
  hostname: 2.2.2.2
  platform: linux

host3:
  hostname: 2.2.2.2
  platform: linux

感谢您的帮助!

python python-3.x bash pyyaml
1个回答
0
投票

我想所有平台都是'linux',因为您没有提供其他详细信息。因此,您可以通过遍历主机来直接获得所需的结果:

hosts = ('1.1.1.1','2.2.2.2','3.3.3.3')

pattern = "host%s:\n  hostname: %s\n  plateform: linux\n"

yaml = "\n".join(pattern % (n+1, host) for n, host in enumerate(hosts))

print(yaml)

结果:

host1:
  hostname: 1.1.1.1
  plateform: linux

host2:
  hostname: 2.2.2.2
  plateform: linux

host3:
  hostname: 3.3.3.3
  plateform: linux
© www.soinside.com 2019 - 2024. All rights reserved.