Home > Software design >  how do i import a csv file with python and not get the error (I/O operation on closed file.) while t
how do i import a csv file with python and not get the error (I/O operation on closed file.) while t

Time:12-07

import csv
with open("insurance.csv", newline = "", ) as insurance_data:
    insurance_reader = csv.DictReader(insurance_data)

Both code sections are in 2 different notebook blocks

#calculate and seperate BMI categories
def bmi_categories(file):
    obese_counter = 0
    overweight_counter = 0
    for item[BMI] in file:
        if item[BMI] > 25 and item[BMI]<= 30:
            overweight_counter  =1
        elif item[BMI] > 30:
            obese_counter  = 1
        else:
            pass
bmi_categories(insurance_data)

I'm trying to create a function that will take the BMIs in the data set which is currently in dictionary format and count how many obese/overweight are in the data set with a function.

CodePudding user response:

DictReader only creates object. As you open file with With statement, that file reader object is closed once code gets below "with" block. Hence you get closed file exception when you try to use it. Solution might be simple: simply move your code which is using insurance_reader under with block.

import csv
with open("insurance.csv", newline = "", ) as insurance_data:
    insurance_reader = csv.DictReader(insurance_data)
    for row in insurance_reader:
        #call function on row here

#here is reader closed, do not use insurance_reader object

Otherwise, for better control I would rather use pandas.read_csv function. with open function, consider using mode='r' to open file in read only mode.

CodePudding user response:

insurance_data is the file descriptor.

You can't use it in the second block as it has been closed in the first one (due to the with statement).

It looks like you want to use the dict you've built in the first block.

Replace bmi_categories(insurance_data) by bmi_categories(insurance_reader).

  • Related