Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
访问系统文件时python中的权限错误_Python_Python 3.x_Error Handling - Fatal编程技术网

访问系统文件时python中的权限错误

访问系统文件时python中的权限错误,python,python-3.x,error-handling,Python,Python 3.x,Error Handling,我正试图用python编写一个程序,在特定时间内阻止某些网站。为此,我必须在windows中更改hosts文件。我使用了以下代码: import time from datetime import datetime as dt hosts_path = "C:\Windows\System32\Drivers\etc" redirect = "127.0.0.1" weblist = ["www.youtube.com", "youtube.com", "www.zoomg.ir",

我正试图用python编写一个程序,在特定时间内阻止某些网站。为此,我必须在windows中更改hosts文件。我使用了以下代码:

 import time
from datetime import datetime as dt
hosts_path = "C:\Windows\System32\Drivers\etc"
redirect = "127.0.0.1"
weblist = ["www.youtube.com", "youtube.com", "www.zoomg.ir",
           "zoomg.ir", "www.rooziato.com", "rooziato.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, 20):
        print("It's working hours")
        with open(hosts_path, "r+") as file:
            content = file.read()
            for website in weblist:
                if website in content:
                    pass
                else:
                    file.write(redirect + " " + website + "\n")
    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 weblist):
                    file.write(line)
            file.truncate()

        print("It's not working hours")

    time.sleep(5)
这是回溯:

File "Blocker.py",line 11min <module>
   with open(hosts_path, "r+") as file:
PermissionError:[Errno13]Permission denied:"C:\Windows\System32\Drivers\etc"
文件“Blocker.py”,第11min行
打开(主机路径,“r+”)作为文件:
权限错误:[Errno13]权限被拒绝:“C:\Windows\System32\Drivers\etc”

我该怎么办?

您正在使用没有权限打开原始文件(文件位于C:\Windows\System32\Drivers)的Windows用户运行脚本

您是否尝试将该文件夹的权限授予您的用户

如果您有权访问管理员用户,请在文件夹C:\Windows\System32\Drivers上向将运行Python脚本的用户授予权限


这可能会有所帮助

似乎不是python特有的问题。我打赌你可以用一个.bat文件复制它。你能给我们看一下回溯吗?你没有访问这个文件的权限。尝试以管理员身份运行shell。然后从中执行python脚本。@Utsav我以管理员的身份运行shell,并且出现了这个错误appeared@FarzinNasiri在代码格式中,而不是在注释中添加对问题的回溯您到
主机的路径不完整。它只进入
etc
,这是一个目录。当然你不能打开它
File "Blocker.py",line 11min <module>
   with open(hosts_path, "r+") as file:
PermissionError:[Errno13]Permission denied:"C:\Windows\System32\Drivers\etc"