0

I'm slowly working through DNA on pset6 and I am running into some issues with the opening/closing of CSVs. I open the CSV using

with open(database, "r") as csv_file:
    csv_reader = csv.DictReader(csv_file)
    headers = csv_reader.fieldnames

but as soon as I come back out of that, presumably the file closes. But then I have problems accessing the dictionary it created.

My code currently goes like this:

with open(database, "r") as csv_file:
    csv_reader = csv.DictReader(csv_file)
    headers = csv_reader.fieldnames

#rest of code here
#rest of code here

but should I actually be doing:

with open(database, "r") as csv_file:
    csv_reader = csv.DictReader(csv_file)
    headers = csv_reader.fieldnames

    #rest of code here
    #rest of code here

Do I only close a file when I have finished the program? I think I am trying to close the file too early (as I am working on the assumption that once it's copied into a dictionary, I can close the file).

Thanks!

0

If you use the with block, that automatically closes the file at its end.

You could place the other code in that with as well just as you assumed, or read the file within and store it in a data structure of your choice for later use, e.g. using a for loop, or simply something like csv_content = list(csv_reader).

Or don't use a with and instead csv_file.close() later, but I prefer with.

| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .