在利用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()
我看了下,原文件沒有關(guān)閉啊。后來突然想起來with open(filename)as f:是自動關(guān)閉的,所以后面的相關(guān)內(nèi)容也應(yīng)該放到這部分。所以調(diào)整后的代碼為:
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()
成功了。