Semantics of file.close()

Evan Klitzke evan at
Wed Jul 18 04:07:32 CEST 2007

On 7/17/07, Hrvoje Niksic <hniksic at> wrote:
> "Evan Klitzke" <evan at> writes:
> > 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.
> But the writes are buffered, and close causes the buffer to be
> flushed.  file.close can throw an exception just like fclose, but it
> will still ensure that the file is closed.

Is this buffering being done by Python or the kernel? AFAIK, the
kernel will return a ENOSPC on a write if there is no space left on a
device, even if the device isn't _really_ full but will be full after
the kernel writes in memory buffers to disk. So a close statement (in
C) should never fail due to a lack of space -- that should be seen on
the write syscall, even if the kernel is doing buffering.

Evan Klitzke <evan at>

More information about the Python-list mailing list