Opening files without closing them
Robert Kern
robert.kern at gmail.com
Mon Mar 6 17:24:25 EST 2006
More information about the Python-list mailing list
Mon Mar 6 17:24:25 EST 2006
- Previous message (by thread): Dr. Dobb's Python-URL! - weekly Python news and links (Mar 6)
- Next message (by thread): Opening files without closing them
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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
- Previous message (by thread): Dr. Dobb's Python-URL! - weekly Python news and links (Mar 6)
- Next message (by thread): Opening files without closing them
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list