reference counting and file objects

Peter peter at monicol.co.uk
Tue May 24 12:50:38 EDT 2005


Martin v. Löwis wrote:
> Paul Rubin wrote:
> >>Consider the function above.  Do I need the fp.close(), or will the
> >>file be closed automatically when fp goes out of scope and its
> >>reference count drops to zero?
> >
> > In CPython, fp gets closed when it leaves scope.
>
> One issue is that when the function terminates through an exception,
> the file stays open as long as the traceback is available, which
> exists until the next exception is raised (and thus replaces this
> traceback).
>
> If the function terminates normally (i.e. through return), it is
> as you say.
>
> Regards,
> Martin

Does the idiom:

lines = file("myfile","r").readlines()

have any better guarantee of being closed automatically? 

Peter




More information about the Python-list mailing list