我試圖用python腳本管理主機文件。我是python的新手,如果找到匹配的話,我很難弄清楚如何替換一條線。例如,如果地址在網站的主機文件中發生更改,我希望腳本找到它並將其更改回來。謝謝你的幫助。Python替換文本文件中的行
import os
import time
#location to the host file to read and write to
hosts_path=r"C:\Windows\System32\drivers\etc\hosts"
#the address I want for the sites
redirect="0.0.0.0"
#the websites that I will set the address for
website_list=["portal.citidirect.com","www.bcinet.nc","secure.banque-tahiti.pf","www.bancatlan.hn","www.bancentro.com.ni","www.davivienda.com.sv","www.davivienda.cr","cmo.cibc.com","www.bi.com.gt","empresas.banistmo.com","online.belizebank.com","online.westernunion.com","archive.clickatell.com"]
#continuous loop
while True:
with open(hosts_path,'r+') as file:
content=file.read()
#for each of the websites in the list above make sure they are in the host file with the correct address
for website in website_list:
site=redirect+" "+ website
#here is where I have an issue, if the website is in the host file but with the wrong address I want to write over the line, instead the program is adding it to the end of the file
if website in content:
if site in content:
pass
else:
file.write(site)
else:
file.write("\n"+site)
time.sleep(300)
os.system('ipconfig /flushdns')
將更改後的行寫入_new_文件,然後在完成時將文件重命名爲舊名稱會更容易。在現有位置更新現有文件非常困難。 –
這裏的問題是您正在讀取整個文件,然後掃描數據。當然,使用這種方法仍然可以解決這個問題,但更快更簡單的方法是按行 –
掃描文件行謝謝你的迴應。約翰戈登我喜歡使用另一個文件的想法。 – jbvo