Search code examples
pythoncsvfileimportvalueerror

How can I resolve this I/O Error in when trying to save a file in python?


I am getting the following error with this code: line 8, in for line in csv_reader: ValueError: I/O operation on closed file

import csv
import re

with open('file.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file)

ff = []
for line in csv_reader:
       ff.append([re.search('mfgcode="(.+?)"', line[0] ).group(1),re.search('modelno="(.+?)"', line[0] ).group(1),re.search('qtyavail="(.+?)"', line[0] ).group(1)])
        
df = pd.DataFrame(ff,columns =['mfgcode','modelno','qtyavail'])
df.to_csv("test.csv",index=False)
print (df)

What could be the error preventing this from saving a file?


Solution

  • your csv_reader is outside the with block.

    Try:

    import csv
    import re
    
    with open('file.csv', 'r') as csv_file:
        csv_reader = csv.reader(csv_file)
    
        ff = []
        for line in csv_reader:
            ff.append([re.search('mfgcode="(.+?)"', line[0] ).group(1),re.search('modelno="(.+?)"', line[0] ).group(1),re.search('qtyavail="(.+?)"', line[0] ).group(1)])
            
        df = pd.DataFrame(ff,columns =['mfgcode','modelno','qtyavail'])
        df.to_csv("test.csv",index=False)
        print (df)