The Python Oracle

ValueError : I/O operation on closed file

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC C Schuberts Piano Sonata No 13 D

--

Chapters
00:00 Question
00:31 Accepted answer (Score 223)
01:02 Answer 2 (Score 10)
01:17 Answer 3 (Score 1)
01:56 Answer 4 (Score 0)
02:30 Thank you

--

Full question
https://stackoverflow.com/questions/1895...

Accepted answer links:
[with]: https://docs.python.org/reference/compou...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #csv #fileio #io

#avk47



ACCEPTED ANSWER

Score 231


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



ANSWER 2

Score 11


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



ANSWER 3

Score 0


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

Save data to a variable(file), so you need a with.




ANSWER 4

Score 0


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.