Paul Rubin wrote: > "3c273" <[EMAIL PROTECTED]> 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 [EMAIL PROTECTED] "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 -- http://mail.python.org/mailman/listinfo/python-list