ValueError : I/O operation on closed file

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.

When I try to write to the file it reports the error:

ValueError: I/O operation on closed file.
513404 次浏览

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

同样的错误 可以由 混音: tab + space 引发。

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

在 PyCharm 中进行调试时,我得到了这个异常,因为没有触发任何断点。为了防止这种情况发生,我在 with块之后添加了一个断点,然后这种情况就停止了。

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

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

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

另一个可能的原因是,在一轮复制面条之后,您最终读取两个文件并分配 两个文件句柄的名称相同,如下所示。注意嵌套的 with open语句。

with open(file1, "a+") as f:
# something...
with open(file2, "a+", f):
# now file2's handle is called f!


# attempting to write to file1
f.write("blah") # error!!

修正方法是为两个文件句柄分配不同的变量名,例如 f1f2,而不是两个 f

我也有同样的问题。 这是我以前的代码

csvUsers = open('/content/gdrive/MyDrive/Ada/Users.csv', 'a', newline='', encoding='utf8')
usersWriter = csv.writer(csvUsers)
for t in users:
NodeWriter=.writerow(users)
csvUsers.close()

显然,我应该写 usersWriter 而不是 NodeWriter。

NodeWriter=.writerow(users)
usersWriter=.writerow(users)

下面是我当前的代码,它正在工作

csvUsers = open('/content/gdrive/MyDrive/Ada/Users.csv', 'a', newline='', encoding='utf8')
usersWriter = csv.writer(csvUsers)
for t in users:
usersWriter=.writerow(users)
csvUsers.close()