For every object in memory, Python keeps a reference count. As long as there are no more references to an object around, it will be garbage collected.
The open()
function returns a file object.
f = open("myfile.txt", "w")
And in the line above, you keep a reference to the object around in the variable f
, and therefore the file object keeps existing. If you do
del f
Then the file object has no references anymore, and will be cleaned up. It'll be closed in the process, but that can take a little while which is why it's better to use the with
construct.
However, if you just do:
open("myfile.txt")
Then the file object is created and immediately discarded again, because there are no references to it. It's gone, and closed. You can't close it anymore, because you can't say what exactly you want to close.
open("myfile.txt", "r").readlines()
To evaluate this whole expression, first open
is called, which returns a file object, and then the method readlines
is called on that. Then the result of that is returned. As there are now no references to the file object, it is immediately discarded again.