File not closed

Chris Angelico rosuav at gmail.com
Wed Mar 20 10:54:28 EDT 2019


On Thu, Mar 21, 2019 at 1:16 AM Grant Edwards <grant.b.edwards at gmail.com> wrote:
>
> On 2019-03-20, ast <none at gmail.com> wrote:
> > Hello
> >
> > In the following snippet, a file is opened but
> > without any variable referring to it.
> > So the file can't be closed.
> >
> > [line.split(":")[0]
> >   for line in open('/etc/passwd')
> >   if line.strip() and not line.startswith("#")]
> >
> > What do you think about this practice ?
>
> If it's a short-lived program, then it will always get closed when the
> program terminates.  Otherwise, it will get (eventually) get closed
> when the garbage collection system cleans up the orphan object.
>
> For short, throw-away progams, that's fine.  For long running servers,
> it's bad style.

What Grant just said is the worst-case, btw. It'll often be closed
more promptly than that, but it's not guaranteed, unless you
explicitly call close() on the file, or (best recommendation) use it
in a 'with' block to ensure that it's closed when you exit.

ChrisA



More information about the Python-list mailing list