ValueError : I/O operation on closed file
PythonCsvFile IoIoPython Problem Overview
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.
Python Solutions
Solution 1 - Python
Indent correctly; your for
statement should be inside the 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)
Outside the with
block, the file is closed.
>>> with open('/tmp/1', 'w') as f:
... print(f.closed)
...
False
>>> print(f.closed)
True
Solution 2 - Python
Same error can raise by mixing: tabs + spaces.
with open('/foo', 'w') as f:
(spaces OR tab) print f <-- success
(spaces AND tab) print f <-- fail
Solution 3 - Python
file = open("filename.txt", newline='')
for row in self.data:
print(row)
Save data to a variable(file
), so you need a with
.
Solution 4 - Python
Another possible cause is the case when, after a round of copypasta, you end up reading two files and assign the same name to the two file handles, like the below. Note the nested with open
statement.
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!!
The fix would then be to assign different variable names to the two file handles, e.g. f1
and f2
instead of both f
.
Solution 5 - Python
I was getting this exception when debugging in PyCharm, given that no breakpoint was being hit. To prevent it, I added a breakpoint just after the with
block, and then it stopped happening.
Solution 6 - Python
I had this problem when I was using an undefined variable inside the with open(...) as f:
.
I removed (or I defined outside) the undefined variable and the problem disappeared.