File not closed

Peter Otten __peter__ at web.de
Wed Mar 20 04:42:23 EDT 2019


ast wrote:

> Hello
> 
> In the following snippet, a file is opened but
> without any variable referring to it.
> So the file can't be closed.

The file will be closed implicitly when the file object gets garbage-
collected:

$ python3
Python 3.4.3 (default, Nov 12 2018, 22:25:49) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open("/etc/passwd")
>>> 
[1]+  Stopped                 python3
$ lsof /etc/passwd
COMMAND  PID  USER   FD   TYPE DEVICE SIZE/OFF    NODE NAME
python3 6815 peter    3r   REG    8,7     2899 8786346 /etc/passwd
$ fg
python3


>>> del f
>>> 
[1]+  Stopped                 python3
$ lsof /etc/passwd
$


> [line.split(":")[0]
>   for line in open('/etc/passwd')
>   if line.strip() and not line.startswith("#")]
> 
> What do you think about this practice ?

While in most cases relying on the gc does not do any harm I still prefer to 
close the file explicitly:

with open("/etc/passwd") as instream:
    stuff = [... for line in instream ...]




More information about the Python-list mailing list