open, close

Piet van Oostrum piet-l at vanoostrum.org
Sat Aug 31 09:43:41 EDT 2019


Max Zettlmeißl <max at zettlmeissl.de> writes:

> On Sat, Aug 31, 2019 at 2:22 PM Manfred Lotz <ml_news at posteo.de> wrote:
>>
>> Could I use the latter as a substitute for the with-construct?
>>
>
> You can't use the second statement as a proper substitute for the first one.
>
> With the context manager, it is ensured that the file is closed. It's
> more or less equal to a "finally" clause which closes the file
> descriptor.
> So as long as the Python runtime environment functions properly, it
> will be closed.
>
> Your second statement on the other hand, is more or less equivalent to:
>
> f = open("foo.txt")
> lines = f.readlines()
>
> Close won't be called.

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.

On the other hand, the with statement guarantees that the file will be closed, so it is the preferred method.

-- 
Piet van Oostrum <piet-l at vanoostrum.org>
WWW: http://piet.vanoostrum.org/
PGP key: [8DAE142BE17999C4]



More information about the Python-list mailing list