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)
Here, p
is a dictionary, w
and c
both are strings.
这里p是字典,w和c都是字符串。
When I try to write in the file it reports error:
当我试图写入文件时,它会报告错误:
ValueError : I/O operation on closed file.
Help me, I'm really new to python. I'm working with Python 2.7.3 Thank you in advance.
帮帮我,我对python很陌生。我正在使用Python 2.7.3,提前谢谢。
2 个解决方案
#1
83
Indent correctly; for
statement should be inside with
block:
正确的缩进;对于语句应该在block中:
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)
Outside the with
block, the file is closed.
在带有块的外部,文件被关闭。
>>> with open('/tmp/1', 'w') as f:
... print f.closed
...
False
>>> print f.closed
True
#2
0
Same error can raise by mixing: tabs + spaces.
同样的错误可以通过混合:制表符+空格来增加。
with open('/foo', 'w') as f:
(spaces OR tab) print f <-- success
(spaces AND tab) print f <-- fail
#1
83
Indent correctly; for
statement should be inside with
block:
正确的缩进;对于语句应该在block中:
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)
Outside the with
block, the file is closed.
在带有块的外部,文件被关闭。
>>> with open('/tmp/1', 'w') as f:
... print f.closed
...
False
>>> print f.closed
True
#2
0
Same error can raise by mixing: tabs + spaces.
同样的错误可以通过混合:制表符+空格来增加。
with open('/foo', 'w') as f:
(spaces OR tab) print f <-- success
(spaces AND tab) print f <-- fail