Domanda

What happens to a file descriptor when I don't assign it to a variable, but I just open it "in line"? How do I close it later?

For instance:

import csv
writer = csv.writer(open('a_file', 'wb'))
for line in some_data:
    writer.writerow(line)

I know I should use with, but what can I do in this particular case to close the file descriptor corresponding to a_file?

È stato utile?

Soluzione

Eventually is garbaged collected.

It is not a good practice to do this, because you may need to flush the contents of a file to be actually written to disk. By letting the garbage collector do its job when it wants, you're not sure when or whether the file will be actually written.

Altri suggerimenti

A file descriptor is like any other object in Python. When a reference to it goes out of scope, the reference count is decremented. When there are no more references to it, it is deleted.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top