Question

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?

Était-ce utile?

La solution

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.

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top