我的输出显示值错误:对关闭的文件执行I/O操作。python

2024-06-11 15:52:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道关于同一个问题有很多问题,但我没有找到解决我问题的答案

我做了一个应用程序,写在主机文件的某些字,但当我来输出程序,它显示关闭的文件 这是我的密码

import time
from datetime import datetime as dt


host_temp = r"C:\Users\ALAA\AppData\Local\atom\app-1.38.2\hello\web site blocker\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,16) < dt.now() < dt(dt.now().year,dt.now().month,dt.now().day,23):
        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)

这里是错误信息

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 20, in <module>
    file.write(redirect + " " + website + "\n")
ValueError: I/O operation on closed file.

Tags: 文件inimportcomwebhostwwwdt
1条回答
网友
1楼 · 发布于 2024-06-11 15:52:47

试试这个:

import time
from datetime import datetime as dt


host_temp = r"C:\Users\ALAA\AppData\Local\atom\app-1.38.2\hello\web site blocker\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,16) < dt.now() < dt(dt.now().year,dt.now().month,dt.now().day,23):
        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)

我缩进了for循环及其内容,因为python不会忽略不正确的缩进

相关问题 更多 >