坑六:ValueError: I/O operation on closed file.

在利用matplotlib作图的时候,有个错误总过不去。ValueError: I/O operation on closed file.

原代码如下:

import csv
filename='sitka_weather_07-2014.csv'
with open(filename) as f:
    reader=csv.reader(f)
    name=next(reader)
      
for no,value in enumerate(name):
    print (no,value)
   
highs=[]

for row in reader:
    high=row[1]
    highs.append(high)

from matplotlib import pyplot as plt
fig=plt.fig(dpi=128,figsize=(10,8))
plt.plot(highs,c='red')
plt.title('the high temperature',fontsize=20)
plt.xlabel('',fontsize=10)
plt.ylabel('high temperature',fontsize=10)
plt.tick_params(axis='both',which='major')

plt.show()

我看了下,原文件没有关闭啊。后来突然想起来with open(filename)as f:是自动关闭的,所以后面的相关内容也应该放到这部分。所以调整后的代码为:

import csv
filename='sitka_weather_07-2014.csv'
with open(filename) as f:
    reader=csv.reader(f)
    name=next(reader)    
    highs=[]
    for row in reader:
        high=row[1]
        highs.append(high)
      
from matplotlib import pyplot as plt
fig=plt.figure(dpi=128,figsize=(10,8))
plt.plot(highs,c='red')
plt.title('the high temperature',fontsize=20)
plt.xlabel('',fontsize=10)
plt.ylabel('high temperature',fontsize=10)
plt.tick_params(axis='both',which='major')

plt.show()
成功了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容