坑六: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()

我看了下,原文件沒有關(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()
成功了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容