2013-09-23 96 views
48
import csv  

with open('v.csv', 'w') as csvfile: 
    cwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) 

for w, c in p.iteritems(): 
    cwriter.writerow(w + c) 

在這裏,p I/O操作是一本字典,wc都是字符串。ValueError異常:在關閉的文件

當我嘗試在文件中寫報告錯誤:

ValueError : I/O operation on closed file. 

幫助我,我真的很新的Python。我正在與Python 2.7.3 預先感謝您。

回答

76

正確縮進; for的說法應該是裏面with塊:

import csv  

with open('v.csv', 'w') as csvfile: 
    cwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) 

    for w, c in p.iteritems(): 
     cwriter.writerow(w + c) 

with塊,文件被關閉。

>>> with open('/tmp/1', 'w') as f: 
...  print f.closed 
... 
False 
>>> print f.closed 
True 
+0

謝謝!你救了我幾個小時的浪費:) – Learner23

+0

不能相信這個錯誤被擡頭了很多次! – user1767754