open, close

Manfred Lotz ml_news at posteo.de
Sat Aug 31 10:41:36 EDT 2019


On Sat, 31 Aug 2019 15:43:41 +0200
Piet van Oostrum <piet-l at vanoostrum.org> wrote:

> 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.
> 


When you say COULD this sounds like it is a matter of luck. My thinking
was that USUALLY the file will be closed after the statement because
then the file handle goes out of scope. 

However, I understand now that in contrary to `with...` there is no
guarantee. 


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

Thanks. So, I take that I'm better off to use 'with...'.

-- 
Manfred








More information about the Python-list mailing list