Closing a file error

Hi,

Is there any reason why I get an error when I use this line of code?

opened_file.close()

I thought once the data is in the read_file, I don’t need the file anymore, so I can close.

Full Code:

opened_file = open('AppleStore.csv')
read_file = reader(opened_file)
opened_file.close()
apps_data = list(read_file)
appsapple_header = apps_data[0]
appsapple_data = apps_data[1:]

Error:

ValueErrorTraceback (most recent call last)
<ipython-input-33-015752f31c0b> in <module>()
      4 read_file = reader(opened_file)
      5 opened_file.close()
----> 6 apps_data = list(read_file)
      7 appsapple_header = apps_data[0]
      8 appsapple_data = apps_data[1:]

ValueError: I/O operation on closed file.

Regards
L.

2 Likes

Here you are trying to read data from file after closing it. Hence exception occurred.

You suppose to close file after reading or storing data so right way is

opened_file = open('AppleStore.csv')
read_file = reader(opened_file)
apps_data = list(read_file)
opened_file.close()

You might be confuse due to this

read_file = reader(opened_file)

This does not mean that read_file has data after running this line. It is just kind of helper function which help you to take data from the file. but does not store it.

3 Likes

Hi

Does this mean that:

read_file = reader(opened_file)

the read_file is still connected to the .csv file until:

apps_data = list(read_file)

So making read_file a list, and then storing it on apps_data (list of list?) mean you can then close the file, because the connection to the .csv file is no longer there?

Regards
L.

Yes we can say that for illustration purpose. But note that internally things are working differently.

1 Like

Can you provide a web link to more information on how this connection works?

Regards
L.

Sorry Did not find any resources about its internal implementation.