Allowing ref counting to close file items bad style?

sjdevnull at sjdevnull at
Fri Sep 1 07:46:44 CEST 2006

Dan wrote:
> BJo:rn Lindqvist wrote:
> > On 8/30/06, Dan <bounces at> wrote:
> >> Is my data safer if I explicitly close, like this?:
> >>      fileptr = open("the.file", "w")
> >>      foo_obj.write(fileptr)
> >>      fileptr.close()
> > Have you ever experienced a problem caused by not explicitly closing
> > your file handles?
> No.  If I had, I wouldn't have asked the question.  It seems to work,
> but can I really count on it?

In CPython, you can rely on file objects to be closed when the last
reference to them is removed.  In general, the language spec does not
guarantee that so if you use Jython or other implementations you cannot
rely on files being closed on last reference.  (see my other posts in
this thread for why I think the language spec should be changed to
guarantee the ref-counting semantics at least in simple cases).

More information about the Python-list mailing list