【问题标题】:My output shows Value Error: I/O operation on closed file. python我的输出显示 Value Error: I/O operation on closed file。 Python
【发布时间】:2019-12-02 23:45:12
【问题描述】:

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

我正在制作一个应用程序来在主机文件上写入某些单词,但是当我输出程序时,它显示该关闭的文件 这是我的代码

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.

【问题讨论】:

  • for website in website_list: 此行不缩进。这是故意的吗?

标签: python python-3.x python-2.7 io output


【解决方案1】:

试试这个:

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 不会忽略不正确的缩进

【讨论】:

  • 太棒了! :) 如果它确实最终解决了您的问题,请务必标记此答案
猜你喜欢
  • 1970-01-01
  • 2021-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-02
  • 2015-11-27
  • 1970-01-01
  • 2018-02-21
相关资源
最近更新 更多