Opening files without closing them

Robert Kern robert.kern at gmail.com
Mon Mar 6 17:24:25 EST 2006


Paul Rubin wrote:
> "3c273" <nospam at nospam.com> writes:
> 
>>>f = open(file)
>>>try:
>>>    contents = f.read()
>>>finally:
>>>    f.close()
>>>
>>
>>Pardon the newbie question, but could you explain why? I have been doing it
>>the same way as the OP and would like to know the difference. Thank you.
> 
> Say that the open is inside the try block.  If the file can't be
> opened, then 'open' raises an exception, 'f' doesn't get set, and then
> the 'finally' clause tries to close f.  f might have been previously
> bound to some other file (which still has other handles alive) and so
> the wrong file gets closed.

And even if 'f' wasn't bound to anything, you will get a NameError instead of
the exception that you're really interested in seeing.

-- 
Robert Kern
robert.kern at gmail.com

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco




More information about the Python-list mailing list