问题: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.items():
cwriter.writerow(w + c)
这里,p
是一本字典,w
并且c
都是字符串。
当我尝试写入文件时,它报告错误:
ValueError: I/O operation on closed file.
回答 0
正确缩进;您的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.items():
cwriter.writerow(w + c)
在with
块外部,文件已关闭。
>>> with open('/tmp/1', 'w') as f:
... print(f.closed)
...
False
>>> print(f.closed)
True
回答 1
混合使用:制表符+空格会引起相同的错误。
with open('/foo', 'w') as f:
(spaces OR tab) print f <-- success
(spaces AND tab) print f <-- fail