open, close

Max Zettlmeißl max at zettlmeissl.de
Sat Aug 31 10:12:15 EDT 2019


On Sat, Aug 31, 2019 at 3:43 PM Piet van Oostrum <piet-l at vanoostrum.org> wrote:
>
> There is a difference here with the construct that the OP mentioned:
>
>       lines = open("foo.txt").readlines()
>
> In that case the file COULD be closed, but there is no guarantee. It depends on garbage collection.
> In your case the file will not be closed as long as there is still a reference to it (as in f). When f disappears and all copies of it as well, the file COULD be closed similarly.
>

Yes, that is correct. I thought about mentioning the garbage
collection and the extra binding for f, but eventually it does not
change the conclusion.
The garbage collection is just too unpredictable to rely upon in any
scenario where you would deal with many open descriptors in a short
period of time e.g. when opening and processing files in a loop.
It is not easy to generalise from such simple examples. After all, if
all the program does is process one file and shut down afterwards,
this would not be an aspect to worry about.



More information about the Python-list mailing list