Patrick
Patrick

Reputation: 4377

python close file descriptor question

I think this question is more of a "coding style" rather than technical issue.

Said I have a line of code:

buf = open('test.txt','r').readlines()
...

Will the file descriptor automatically close, or will it stay in the memory? If the file descriptor is not closed, what is the prefer way to close it?

Upvotes: 27

Views: 43070

Answers (5)

jsa
jsa

Reputation: 399

You can also try using os.close(fd) method.

Upvotes: 3

Lennart Regebro
Lennart Regebro

Reputation: 172209

It will be automatically closed, but it depends on implementation exactly when. It's nicer to explicitly use a with-block, but if you are just writing a small script for yourself that you run occasionally it doesn't really matter.

Upvotes: 2

John La Rooy
John La Rooy

Reputation: 304137

Usually in CPython, the file is closed right away when the reference count drops to zero (although this behaviour is not guaranteed for future versions of CPython)

In other implementations, such as Jython, the file won't be closed until it is garbarge collected, which can be a long time later.

It's poor style to have code that works differently depending on the implementation's behaviour.

If it's just for a quickie script or something you are trying in the interpreter shell it's good enough, but for any sort of production work you should usually use a context manager as in Falmarri's answer

Upvotes: 17

sahhhm
sahhhm

Reputation: 5365

If you assign the file object to a variable, you can explicitly close it using .close()

f = open('test.txt','r')
buf = f.readlines()
f.close()

Alternatively (and more generally preferred), you can use the with keyword (Python 2.5 and greater) as mentioned in the Python docs:

It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks:

>>> with open('test.txt','r') as f:
...     buf = f.readlines()
>>> f.closed
True

Upvotes: 45

Falmarri
Falmarri

Reputation: 48559

It will stay in memory until the garbage collector closes it. You should always explicitly close your file descriptors. Just do something like this:

with open('test.txt', 'r') as f:
    buf = f.readlines()

Upvotes: 6

Related Questions