ValueError:关闭文件的I / O操作

时间:2013-09-23 06:08:21

标签: python csv file-io 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)

此处p是字典,wc都是字符串。

当我尝试在文件中写入时,它报告错误:

ValueError : I/O operation on closed file.

帮助我,我是python的新手。我正在使用Python 2.7.3 先感谢您。

5 个答案:

答案 0 :(得分:110)

正确缩进; 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)

with块之外,文件已关闭。

>>> with open('/tmp/1', 'w') as f:
...     print f.closed
... 
False
>>> print f.closed
True

答案 1 :(得分:2)

同样的错误可以通过混合:标签+空格来提升。

with open('/foo', 'w') as f:
 (spaces OR  tab) print f       <-- success
 (spaces AND tab) print f       <-- fail

答案 2 :(得分:0)

在PyCharm中进行调试时,由于没有断点,我遇到了这个异常。为了防止这种情况,我在with块之后添加了一个断点,然后它停止了发生。

答案 3 :(得分:0)

file = open("filename.txt", newline='')
for row in self.data:
    print(row)

将数据保存到变量(file)中,因此您需要一个with

答案 4 :(得分:0)

当我在 with open(...) as f: 中使用未定义的变量时遇到了这个问题。 我删除了(或者我在外面定义了)未定义的变量,问题就消失了。

相关问题