open, close

Max Zettlmeißl max at zettlmeissl.de
Sat Aug 31 09:20:41 EDT 2019


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.



More information about the Python-list mailing list