首页 > 解决方案 > 如何从文本文件中列出的数据创建 YAML 文件?

问题描述

我有一个文件 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: 3.3.3.3
  platform: linux

标签: pythonpython-3.xbashruamel.yaml

解决方案


我想所有的平台都是'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

推荐阅读