python - 如何从文本文件中列出的数据创建 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
解决方案
我想所有的平台都是'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
推荐阅读
- kotlin - 使用类字段的 Kotlin 数据类设置器
- python - 无法通过 Python 使用 IEDriverServer 和 Selenium 提取页面标题和 page_source
- android - 如何获取使用 Android 和 Firebase 上传的多个图像的下载 URL
- java - 双链表删除
- excel - 复制另一个单元格中引用的命名范围的值
- python - 在 python 中的某个时间限制后终止并在 ILOG 中检索解决方案
- guid - 如何使用 Java 从 BMC Remedy 用户获取用户 ID 或 GUID
- html - 表格行隐藏在导航栏下
- flutter - Javascript“2020 年 2 月 15 日星期六 14:01:19 GMT+0300(东非时间)”颤动的日期格式类型
- python - Python Regex - 用另一个单词替换特定单词(没有哈希)