Python ValueError : 关闭文件的 I/O 操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18952716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:23:35 来源:igfitidea点击:
ValueError : I/O operation on closed file
提问by GobSmack
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)
Here, p
is a dictionary, w
and c
both are strings.
这里,p
是一本字典,w
并且c
都是字符串。
When I try to write to the file it reports the error:
当我尝试写入文件时,它报告错误:
ValueError: I/O operation on closed file.
采纳答案by falsetru
Indent correctly; your for
statement should be inside the with
block:
正确缩进;你的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)
Outside the with
block, the file is closed.
在with
块之外,文件被关闭。
>>> with open('/tmp/1', 'w') as f:
... print(f.closed)
...
False
>>> print(f.closed)
True
回答by Slake
Same errorcan raise by mixing: tabs + spaces.
通过混合可以引发相同的错误:制表符 + 空格。
with open('/foo', 'w') as f:
(spaces OR tab) print f <-- success
(spaces AND tab) print f <-- fail