Re: Opening files without closing them
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: Opening files without closing them

From: 3c273 <nospam@nospam.com>
Date: Tue Mar 07 2006 - 19:33:25 CET

"Robert Kern" <robert.kern@gmail.com> wrote in message
news:mailman.2794.1141683892.27775.python-list@python.org...
> Paul Rubin wrote:
> > 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.

Thanks to both of you. So in order to be thorough, should I be doing:
try:
    f=open('file')
except: IOError:
    print 'doesn't exist'
    so_something_else_instead()

try:
    contents = f.read()
finally:
    f.close()

Thanks again.
Louis
Received on Sun Apr 30 11:06:11 2006