Gob*_*ack 91 python csv io file-io
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)
Run Code Online (Sandbox Code Playgroud)
这里,p是一本字典,w并且c都是字符串.
当我尝试在文件中写入时,它报告错误:
ValueError : I/O operation on closed file.
Run Code Online (Sandbox Code Playgroud)
帮助我,我是python的新手.我正在使用Python 2.7.3提前谢谢你.
fal*_*tru 127
缩进正确; 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)
Run Code Online (Sandbox Code Playgroud)
在with块外,文件已关闭.
>>> with open('/tmp/1', 'w') as f:
... print f.closed
...
False
>>> print f.closed
True
Run Code Online (Sandbox Code Playgroud)
混合使用:制表符+空格会引起相同的错误。
with open('/foo', 'w') as f:
(spaces OR tab) print f <-- success
(spaces AND tab) print f <-- fail
Run Code Online (Sandbox Code Playgroud)