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

Viewed 101
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.
2 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

You are trying to read the file after it's closed (outside the with block)

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
Related