报错‘I/O operation on closed file’的原因及解决方法咨询
错误原因及解决方法
问题根源
你遇到的I/O operation on closed file错误,核心原因是**with语句的作用域限制**:
with open(...) as fp代码块执行结束后,Python会自动关闭文件对象fp- 你在
with块内初始化了csv.reader(fp),但遍历reader生成数据列表的操作却放在了with块外,此时文件已关闭,reader无法再读取数据,因此触发I/O错误。
修复后的代码
将读取数据的逻辑移到with块内部,确保文件在打开状态下完成数据读取:
import csv # 注意:必须导入csv模块,否则会触发NameError def read_in_csv(csv_file): with open(csv_file, 'r', encoding='utf-8') as fp: reader = csv.reader(fp, delimiter=',', quotechar='"') data_read = [row for row in reader] # 移至with块内执行 return data_read def get_data(filename): data = read_in_csv(filename) data_dict = {} for row in data[1:]: category = row[0] text = row[1] if category not in data_dict: # 简化判断:直接检查键是否在字典中,无需调用.keys() data_dict[category] = [] data_dict[category].append(text) return data_dict bbc_dataset= r'C:\Users\A_A_A\Downloads\bbc-text.csv' data_dict = get_data(bbc_dataset)
额外优化提示
- 务必导入
csv模块,否则会出现NameError: name 'csv' is not defined错误 - 判断字典键是否存在时,
if category not in data_dict比if category not in data_dict.keys()更高效,因为字典本身支持直接判断键的存在性
内容的提问来源于stack exchange,提问作者Python-data
相关产品推荐
相关产品推荐

