ValueError:closures文件的I / O操作

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是字典, wc都是string。

当我尝试写入文件时,报告错误:

 ValueError : I/O operation on closed file. 

帮助我,我真的是新的python。 我正在使用Python 2.7.3预先感谢您。

正确缩进; for声明应该在块内:

 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 block之外,文件被closures。

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