python close file descriptor question

2019-01-06 14:24发布

问题:

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?

回答1:

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


回答2:

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



回答3:

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()


回答4:

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.