Semantics of file.close()

Evan Klitzke evan at yelp.com
Tue Jul 17 19:50:11 CEST 2007


On 7/16/07, seerdecker at gmail.com <seerdecker at gmail.com> wrote:
> Hello,
>
> I'm a Python beginner and I'm trying to open, write and close a file
> in a
> correct manner. I've RTFM, RTFS, and I've read this thread:
> http://groups.google.ca/group/comp.lang.python/browse_thread/thread/73bbda2c920521c/98c731229d86b01d?lnk=st&q=python+file+explicit+close&rnum=1&hl=en#98c731229d86b01d
>
> I still cannot figure out the semantic of file.close(). As far as I
> can
> tell it is undocumented. Explanations and example follow.
>
> There are two occasions where you have to close a file:
>
> 1) At the end of a series of writes to the file, to ensure that all
> data
>    is written correctly to disk. In this case I want file.close() to
>    throw an exception if the file cannot be written (e.g. when there
> is
>    no more disk space).
>
> 2) To clean up after an error occurred during the processing. In that
>    case I just want to close the file handle cleanly. I do NOT want an
>    exception to be thrown (e.g. in my finally clause).
>
> Man page of fclose() -- in C:
>
>   fclose - close a stream
>
>   Upon successful completion 0 is returned.  Otherwise, EOF is
> returned
>   and the global variable errno is set to indicate the error.  In
> either
>   case any further access (including another call  to  fclose())  to
>   the  stream results in undefined behaviour.
>
> The man page of fclose() clearly indicates that fclose() may fail.
> I've
> already tested under Linux that fwrite() indicates success even if the
> disk is full; the error is ONLY reported when close() is called.
>
> Consider the following example:
>
>     file1 = None;
>     file2 = None;
>
>     try:
>     file1 = open("foo1.txt", "wb");
>     file2 = open("foo2.txt", "wb");
>     file1.close();
>     file2.close();
>
>     finally:
>     if file1: file1.close();
>     if file2: file2.close();
>
> How do I ensure that the close() methods in my finally clause do not
> throw an exception?
>
> Thanks a lot,
> Laurent Birtz

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.

-- 
Evan Klitzke <evan at yelp.com>



More information about the Python-list mailing list