如何修复Python读取CSV时出现的“I/O Operation On Closed File”错误
错误原因
with open() 是Python的文件上下文管理语法,当代码执行跳出with的缩进块时,打开的文件会被自动关闭。你当前的for row in reader遍历代码写在了with块外面,此时文件已经关闭,对reader对象做迭代读取就会触发I/O operation on closed file报错。
修正方案
将所有需要读取csv文件内容的代码缩进,放到with open()的代码块内部即可,修正后的完整代码如下:
import matplotlib.pyplot as plt from datetime import datetime import csv first_date = datetime.strptime("1960", "%Y") filename = "/Users/tgiedraitis/Downloads/API_SP.ADO.TFRT_DS2_en_csv_v2_2602143/API_SP.ADO.TFRT_DS2_en_csv_v2_2602143.csv" with open(filename) as f: reader = csv.reader(f) header_row = next(reader) dates = [] for row in reader: dates.append(row[3]) print(dates) for index, column_header in enumerate(header_row): print(index, column_header) # 绘图逻辑不涉及文件操作,可放在with块外 fig = plt.figure(dpi=128, figsize=(10,6)) plt.plot(dates, c="red") plt.title("1960年全球青少年生育率", fontsize=24) plt.xlabel("", fontsize=16) plt.ylabel("平均生育率", fontsize=16) plt.tick_params(axis="both", which="major", labelsize=16) plt.show()
额外优化建议
当前你读取的dates为字符串类型,如果后续需要对X轴做时间序列相关的格式调整,可以在读数据时直接转成datetime格式:dates.append(datetime.strptime(row[3], "%Y")),根据你实际的日期格式调整匹配的格式化字符串即可。
内容的提问来源于stack exchange,提问作者code
相关产品推荐
相关产品推荐

