[英]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(“輸入文件中的主機名”)時,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.