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.
最佳答案
正确缩进;您的 for
语句应该在 with
内 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.items():
cwriter.writerow(w + c)
在 with
block 之外,文件被关闭。
>>> with open('/tmp/1', 'w') as f:
... print(f.closed)
...
False
>>> print(f.closed)
True
关于python - 值错误 : I/O operation on closed file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18952716/