Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

python - PermissionError: [Errno 13] Permission denied: 'C:\Windows\System32\drivers\etc\hosts'

I am trying to run a program that needs to access to the administrator folder but my administrator folder needs a permssion in order to access to the file that I want to edit it using python, and this what appears to me when i run the program PermissionError: [Errno 13] Permission denied: 'C:WindowsSystem32driversetchosts', look you can see in my code i have provided the path to the file that i wanna edit it, the file is "hosts" so how i can run this program ?and I provided the code just in case.

import time
from datetime import datetime as dt


hosts_path = "C:WindowsSystem32driversetchosts"

redirect = "127.0.0.1"


website_list =["www.facebook.com", "facebook.com",
 "dub119.mail.live.com", "www.dub119.mail.live.com",
 "www.gmail.com", "gmail.com"]

while True:

    
    if dt(dt.now().year, dt.now().month, dt.now().day, 8)< dt.now() < dt(dt.now().year, dt.now().month, dt.now().day, 16):
        print("Working hours...")
        with open(hosts_path, 'r+') as file:
            content = file.read()
            for website in website_list:
                if website in content:
                    pass
                else:
                    
                    file.write(redirect + " " + website + "
")
    else:
        with open(hosts_path, '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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...