Opening files without closing them

Paul Rubin http
Mon Mar 6 23:14:01 CET 2006


"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.



More information about the Python-list mailing list