Semantics of file.close()

seerdecker at seerdecker at
Tue Jul 17 01:35:45 CEST 2007


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:

I still cannot figure out the semantic of file.close(). As far as I
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
   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
   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
  and the global variable errno is set to indicate the error.  In
  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.
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;

    file1 = open("foo1.txt", "wb");
    file2 = open("foo2.txt", "wb");

    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

More information about the Python-list mailing list