Ricky Robinson
Ricky Robinson

Reputation: 22933

python: close a file descriptor not assigned to any variable

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?

Upvotes: 3

Views: 209

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 600041

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.

Upvotes: 1

Paulo Bu
Paulo Bu

Reputation: 29804

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.

Upvotes: 4

Related Questions