How to keep a file open

Hi All,

I am working on the medical insurance costs dataset portfolio project and am getting very confused by files. The console will only print the result of one of the functions. I do not understand why. Any help would be appreciated!

import csv

with open("insurance.csv") as insurance:
    data = csv.DictReader(insurance)
    def list_regions():
        for x in data:
            print(x["region"])

    def average_age():
        age_list = []
        total_age = 0
        for x in data:
            age_list.append(x["age"])
            a = int(x["age"])
            total_age += a
        return total_age

    print(average_age())
    print(list_regions())

It likely has to do with how with works. Generally we wouldn’t be defining functions within its body. Define them beforehand and call them from within the with body.

import csv

def list_regions(sample):
  pass
def average_age(sample):
  pass

with open("insurance.csv") as insurance:
    data = csv.DictReader(insurance)
    print (average_age(data))
    list_regions(data)

When the last line has run, with will automatically close the file.

Or, handle the two functions after letting it close the file.

with open("insurance.csv") as insurance:
    data = csv.DictReader(insurance)

print (average_age(data))
list_regions(data)
1 Like