坑六: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()
成功了。

你可能感兴趣的:(坑六:ValueError: I/O operation on closed file.)