簡體   English   中英

如何打開文件,替換該文件中的字符串,然后使用Python將其寫入新文件

[英]How can I open a file, replace a string in that file and write it to a new file using Python

我已經編寫了這個小腳本來打開一個遍歷列表的文件,並根據列表“ hostnames.txt”中的名稱創建新文件。 現在,我需要能夠讀取一個單獨的文件,我們將其稱為“模板”,然后搜索並替換單詞“ hostname”,並將其替換為從“ 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
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的內容讀入列表tdata。

當我們逐步訪問hostnames.txt(“輸入文件中的主機名”)時,

  • 在分配給系統之前,先從主機名中刪除換行符,
  • 用句柄computername打開文件.test
  • 遍歷tdata,將字符串“ hostname”替換為主機(系統)的實際名稱后,將每一行寫到computername
  • 關閉通過句柄計算機名打開的文件
  • 打印主機名並增加count_lines

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM