Semantics of file.close()

Donn Cave donn at
Tue Jul 17 23:44:40 CEST 2007

In article <mailman.794.1184694633.22759.python-list at>,
 "Evan Klitzke" <evan at> wrote:
> > How do I ensure that the close() methods in my finally clause do not
> > throw an exception?

> You should take a look at the man pages for close(2) and write(2) (not
> fclose). Generally you will only get an error in C if you try to close
> a file that isn't open. In Python you don't even have to worry about
> that -- if you close a regular file object more than once no exception
> will be thrown, _unless_ you are using os.close(), which mimics the C
> behavior. If you are out of space, in C you will get an error returned
> by the call to write (even if the data isn't actually flushed to disk
> yet by the kernel). I'm pretty sure Python mimics this behavior, so an
> exception would be called on the write, not on the close operation.

No, he went to the trouble to test this, and he knows how it works. C 
library I/O can return a disk full error on close, because the last of
the buffer will be flushed with write(2), and Python should raise an
exception at this point.

I don't think there's any remedy for it, other than the obvious -
either always flush, or wrap an explicit close in its own exception

   Donn Cave, donn at

More information about the Python-list mailing list