close

[Solved] ValueError : I/O operation on closed file

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error ValueError : I/O operation on closed file in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How ValueError : I/O operation on closed file Error Occurs?

Today I get the following error ValueError : I/O operation on closed file in python.

How To Solve ValueError : I/O operation on closed file Error ?

  1. How To Solve ValueError : I/O operation on closed file Error ?

    To Solve ValueError : I/O operation on closed file Error Indent correctly; your for statement should be inside the with block:

  2. ValueError : I/O operation on closed file

    To Solve ValueError : I/O operation on closed file Error Indent correctly; your for statement should be inside the with block:

Solution 1

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

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

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read