【问题标题】:How can I open a file, replace a string in that file and write it to a new file using Python如何打开文件,替换该文件中的字符串并使用 Python 将其写入新文件
【发布时间】:2015-06-08 19:39:20
【问题描述】:

我编写了这个小脚本来打开一个文件,遍历一个列表并根据列表“hostnames.txt”中的名称创建新文件。现在我需要能够读取一个单独的文件,我们将调用“模板”并搜索并将单词“主机名”替换为从“Hostnames.txt”文件中获取的实际主机名。然后输出具有该主机名的文件实际上在创建的新文件。同样在创建文件时,它会添加一个“?”在添加“.test”之前的主机名末尾,我不知道它来自哪里。

import sys
input_file = open ('hostnames.txt', 'r')
template = open ('hosttemplate.txt', 'r')
count_lines = 0
for hostname in input_file:
        system = hostname
        computername = open(system.strip()+".test",'a')
        computername.write("need to write data from template to file and replace the string hostname with the hostname from hostnames.txt")
        print hostname
        count_lines += 1
print 'number of lines:', count_lines

【问题讨论】:

  • 您确定它是一个? 而不仅仅是一个不可打印的字符吗?您如何查看文件、文本编辑器或什么?该文件是否来自其他操作系统?
  • ? 可能是换行符,至少在ls 等中是这样显示的。如果您迭代文本文件的行,则尾随换行符是行字符串的一部分。试试system = hostname.strip()。附加说明:hostnames.txt 的内容是否可信?
  • 是的,他们值得信赖,这是我根据所需数据亲自创建的文件列表。它实际上是我编译用来创建文件的“主机名”列表。
  • 你如何选择哪个主机名应该放在哪里?
  • 在我的模板文件中,我使用了“主机名”这个词,我需要遍历 2 个文件并从这两个文件中获取数据并将其放入一个“新文件”中。

标签: python string file replace


【解决方案1】:
import sys
input_file = open ('hostnames.txt', 'r')
template = open ('hosttemplate.txt', 'r')
tdata = template.readlines()
count_lines = 0
for hostname in input_file:
        system = hostname.strip()
        computername = open(system+".test",'a')
        for line in tdata:
            computername.write(line.replace('hostname', system))
        computername.close()
        print hostname
        count_lines += 1
print 'number of lines:', count_lines

在循环之前,我们打开hostnames.txt,将hosttemplate.txt的内容读入list tdata。

当我们单步执行 hostnames.txt(“输入文件中的主机名”)时,我们

  • 在分配给系统之前从主机名中去除换行符,
  • 使用句柄计算机名打开文件 .test
  • 遍历 tdata,将字符串 'hostname' 替换为主机(系统)的实际名称后,将每一行写入计算机名
  • 关闭通过句柄计算机名打开的文件
  • 打印主机名并增加 count_lines

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-27
    • 2019-04-05
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-08
    相关资源
    最近更新 更多