【问题标题】:Replace a string in Yaml file using python使用 python 替换 Yaml 文件中的字符串
【发布时间】:2021-04-12 21:26:46
【问题描述】:

我正在尝试使用 python 替换我的 yaml 文件中的字符串,yaml 文件如下所示

文件:a.yml

- hosts: computer1
  history: delete 

  tasks:
    - include: files/docker.yml
    - include: files/ansible.yml
    - include: files/wonder.yml

所以我想将“files/docker.yml”替换为“bin/docker.yml”,其余部分类似。我试过了

fin = open("a.yml", "rt")
fopen = open("a.yml", "wt")
for line in fin:
    fopen.write(line.replace('files/', 'bin'))
fin.close()
fopen.close()

但是这种平静的代码正在把它变成一个空白文件。有什么建议吗?

【问题讨论】:

  • 您可能想重新阅读文件指针的处理方式。然后一次全部读入字符串,并将替换后的字符串写回同一个文件。

标签: python ansible yaml


【解决方案1】:

你可能会使用

with open("a.yml", "rt") as fp:
    content = fp.read()
    content = content.replace("files/", "bin/")

with open ("a.yml", "wt") as fp:
    fp.write(content)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-21
    • 2019-10-11
    • 1970-01-01
    • 2015-11-24
    • 2022-11-25
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多