-1

i'm writing a program that write some website inside hosts file but when i'm trying run the program it's show me an error that the directory is not found

import time
from datetime import datetime as dt

host_temp = "hosts"
host_path = r"C:\Windows\System32\drivers\etc\hosts"
redirect = "127.0.0.1"
website_list = ["www.facebook.com","www.instagram.com", "www.youtube.com"]

while True:
    if dt(dt.now().year,dt.now().month,dt.now().day,20) < dt.now() < dt(dt.now().year,dt.now().month,23,1):
        print("Working hours!!!")
        with open(host_temp, "r+") as file:
            content = file.read()
        for website in website_list:
            if website in content:
                pass
            else:
                file.write(redirect + " " + website + "\n")
    else:
        print("Fun hours!!!")
    time.sleep(5)

and this is the output

Working hours!!!
Traceback (most recent call last):
  File "C:\Users\ALAA\AppData\Local\atom\app-1.38.2\hello\web site blocker\web_site_blocker.py", line 12, in <module>
    with open(host_temp, "r+") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'hosts'
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Alaa KM
  • 43
  • 1
  • 7

2 Answers2

1

This error has nothing to do with the structure of your program. It is just saying that it cannot find the file you say exists. You need to check the filetype of your file (you can usually see it next to your file name or in the file's properties). The majority of files have an extension.

If your file is a text file (.txt), for example, your filename would be:

host_temp = "hosts.txt"
Akaisteph7
  • 5,034
  • 2
  • 20
  • 43
0

seems like your code should be like below with full path. if you don't provide full path then python will search for 'hosts' file where your py file is stored.

with open(host_path, "r+") as file:
Praveen
  • 346
  • 1
  • 6
  • 18