IT-Swarm.Net

ValueError:关闭文件的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都是字符串。.

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

ValueError : I/O operation on closed file.

帮助我,我是python的新手。我正在使用Python 2.7.3提前谢谢你。.

76
GobSmack

缩进正确; 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
108
falsetru

快速,可靠且价格合理的云托管

注册并在30天内获得$50奖金!

相同的错误 可以通过 混合 :制表符+空格来提升。.

with open('/foo', 'w') as f:
 (spaces OR  tab) print f       <-- success
 (spaces AND tab) print f       <-- fail
2
Slake