我试图用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