[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

File not closed

>> On 2019-03-20, ast <none at gmail.com> wrote:
>>> 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 ?

As others have agreed, the lack of close() is not good practice, even if 
it is unlikely to reduce anyone to tears.

Two other points, if I may:

1 it is a fairly complex line, having been split into three. If it is 
simplified into an explicit foreach-loop, then a file-handle becomes 
necessary - and can be closed. NB The greatest benefit there lies in the 
(not a reflection on you, but thinking of 'future-readers')

2 this (revealed snippet of) code will fail on a huge number of 
machines. [insert comment about the superiority of Linux/the failings of 
MS-Windows, here] Accordingly, it should be wrapped into a try...except 
block. That being the case, by unwinding the foreach-loop (1) and adding 
try...finally, it'll 'tick all your boxes'! There's also room for an 
illuminating (and educational) "I can't do that Dave" errmsg...

(despite my also being a fan of context-managers, per previous advice!)

Regards =dn