我有一个文件主机名.txt包含以下内容:
1.1.1.1
2.2.2.2
3.3.3.3
希望在主机名.yaml 文件中采用以下格式,最好使用 python(bash shell 也可以(。
host1:
hostname: 1.1.1.1
platform: linux
host2:
hostname: 2.2.2.2
platform: linux
host3:
hostname: 3.3.3.3
platform: linux
由于 YAML 文件是文本文件,因此原则上可以使用标准编写这些文件 Python 输出例程。但是,您需要了解以下所有详细信息 YAML 规范,以便使其成为有效的 YAML 文件。
对于您的示例来说,这相对简单,但这只是因为您这样做了 没有击中任何需要报价的 YAML 特价。
缺乏对 YAML 规范的详细了解,最好是 坚持使用 YAML 加载器/转储程序库。一个库支持 YAML 1.2标准是ruamel.yaml(免责声明:我是 那个包(。
安装后(在 Python 虚拟环境中使用pip install ruamel.yaml
(,您可以执行以下操作:
from pathlib import Path
import ruamel.yaml
in_file = Path('hostname.txt')
out_file = in_file.with_suffix('.yaml')
yaml = ruamel.yaml.YAML()
data = {}
index = 0
for line in in_file.open():
line = line.strip()
index += 1
data[f'host{index}'] = dict(hostname=line, platform='linux')
yaml.dump(data, out_file)
这给了:
host1:
hostname: 1.1.1.1
platform: linux
host2:
hostname: 2.2.2.2
platform: linux
host3:
hostname: 3.3.3.3
platform: linux
请注意,第三个条目的主机名(IP地址?(与您的示例不同, 因为我不知道您希望您的程序如何重复第二个值而不使用 输入文件中的第三个值。
我想所有的平台都是"linux",因为你没有提供额外的细节。因此,您可以通过循环主机来非常简单地获得最终结果:
hosts = ('1.1.1.1', '2.2.2.2', '3.3.3.3')
pattern = "host%s:n hostname: %sn plateform: linuxn"
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