Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting "ValueError: I/O operation on closed file"

Tags:

python

file

import csv
    
with open('MOCK_DATA.csv','r') as f:
    mockDataReader = csv.reader(f)

lineCount = 1

for row in mockDataReader:
    if lineCount > 1:
      print(row)
      lineCount += 1

It gives me an error. Here is the error message:

Traceback (most recent call last):
  File "c:\Users\python programe\.vscode\readingCsvfile.py", line 8, in <module>
    for row in mockDataReader:
ValueError: I/O operation on closed file.
like image 744
pravin Avatar asked Dec 22 '25 15:12

pravin


1 Answers

The with context block closes the file when you exit it. You should nest all the following code that uses the reader you've opened under it:

with open('MOCK_DATA.csv','r') as f:
    mockDataReader = csv.reader(f)

    lineCount = 1
    
    for row in mockDataReader:
        if lineCount > 1:
          print(row)
          lineCount += 1
like image 107
Mureinik Avatar answered Dec 24 '25 05:12

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!