Unable to edit a local hosts file with python
I am trying to build a programme that would block certain websites in a specific working time frame. I am first testing the modifications on a hosts file (located here C:\Users\Alberto\Documents\Atom\web-blocker) that I have copied in the same file as my programme, before modifying the main hosts file. However, even though my script allows me to properly print out the message while I am in working hours or when I am not, the problem is that the websites list are not printed out in the local hosts file. Also, I run the programme as an administrator.
Here is my code:
import time from datetime import datetime as dt hosts_temp="hosts" hosts_path=r"C:\Windows\System32\drivers\etc\hosts" redirect="127.0.0.1" website_list=["www.facebook.com","facebook.com","youtube.com","www.youtube.com"] while True: if dt(dt.now().year,dt.now().month,dt.now().day,6) < dt.now() < dt(dt.now().year,dt.now().month,dt.now().day,19): print("Working hours, get back to work you future data scientist!") with open(hosts_temp,"r+") as file: content=file.read() for website in website_list: if website in content: pass else: file.write(redirect+" "+ website +"\n") else: with open(hosts_temp, 'r+') as file: content=file.readlines() file.seek(0) for line in content: if not any(website in line for website in website_list): file.write(line) file.truncate() print("Fun hours...") time.sleep(5)
What am I missing in order to modify the local hosts file? Thank you in advance for your help.