when I use this code in IPython3 shell
>>>data = open('file').read()
and then check open file descriptors:
lsof | grep file
I find empty list
and when I use this:
>>>open('file')
lsof shows two items. The question is why first operation closes fd while second doesn’t? I supposed that garbage collector must delete file object with no refs.
I know about ‘_’ var in interpreter, when I reassign value
>>>111
>>>_
111
but descriptors remain open.
when I repeat
>>>open('file')
n times there are 2 * n opened descriptors
In the second example the file handle is retained by the interactive interpreter variable
_, which allows you to access the last evaluated expression. If you evaluate another expression, such as1+1, you will note that the file is no longer reported bylsofas open.As pointed out by Mike Byers, this behavior is specific to CPython, and even then to precise circumstances of how the file object is used. To make sure the file is closed regardless of how the code is executed, use a
withstatement: