title: Python replace line in text file
body: <p>I am trying to manage a host file with a python script. I am new to python and I am having a hard time with figuring out how to replace a line if I find a match. For example, if the address gets changed in a host file for a website I want the script to find it and change it back. Thanks for your help.</p>
  
  <pre><code>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')
  </code></pre>