open, close

Grant Edwards grant.b.edwards at gmail.com
Sat Aug 31 10:36:26 EDT 2019


On 2019-08-31, Manfred Lotz <ml_news at posteo.de> wrote:
> Hi there,
> This is a beginner question.
>
> I learned that 
>
> with open("foo.txt") as f:
>         lines = f.readlines()
>
> using the with-construct is the recommended way to deal with files
> making sure that close() always happens.

More importantly, it makes sure that close() always happens at a
particular point. It gets closed when the block after with [...]: exits.

> lines = open("foo.txt").readlines()

In that example, close() will very probably happen sometime soon when
the system notices that there are no remaining references to the
file-object.  In the general case, it's not wise to depend on that for
large complex programs.

For small throw-away scripts it's fine if you know the program will
terminate soon and that having the file open until then isn't an
issue.  For example, if the program is something trivial like this

    import sys
    lines = open(sys.argv[1]).readlines()
    sys.stdout.write("there are %d lines\n" % len(lines))

then it's fine.  The file will get closed when the program exits.

--
Grant




More information about the Python-list mailing list