You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中for循环报错ValueError: 对已关闭文件执行I/O操作

解决"ValueError: I/O operation on closed file."问题

你的问题根源很明确:task_list.close()被放在了for循环内部。第一次循环迭代时,文件句柄就被关闭了,后续循环尝试读取已经关闭的文件,直接触发ValueError。

把task_list.close()移到循环外是完全正确的修改方式,这样所有行读取完成后才会关闭文件。修改后的代码如下:

elif menu == 'va': 
    task_list = open("tasks.txt", "r+") #opens task file
    for line in task_list:        
        assignee, title, description, due_date, date, completed = line.split(", ")
        print(f'''
        Name: {assignee}
        Title: {title}
        Description: {description}
        Due Date: {due_date}
        Date Assigned: {date}
        Task Complete: {completed}''')
    task_list.close()  # 所有行读取完成后再关闭文件

不过更推荐使用Python的**上下文管理器(with语句)**来处理文件操作,它会自动在代码块执行完毕后关闭文件,彻底避免手动管理文件关闭的失误,代码更简洁也更安全:

elif menu == 'va': 
    with open("tasks.txt", "r+") as task_list:
        for line in task_list:        
            # 先去除行尾的换行符,避免split后出现空元素或多余换行
            line = line.strip()
            assignee, title, description, due_date, date, completed = line.split(", ")
            print(f'''
            Name: {assignee}
            Title: {title}
            Description: {description}
            Due Date: {due_date}
            Date Assigned: {date}
            Task Complete: {completed}''')

额外提醒:如果tasks.txt中存在格式不规范的行(比如分隔符不一致、多余空格),split(", ")可能会抛出ValueError(元素数量不匹配),可以考虑添加异常处理来增强代码鲁棒性。

内容的提问来源于stack exchange,提问作者johnbernard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 11:55:24