On Thu, Mar 21, 2019 at 1:16 AM Grant Edwards <grant.b.edwa...@gmail.com> wrote: > > On 2019-03-20, ast <n...@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 -- https://mail.python.org/mailman/listinfo/python-list