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 -- http://mail.python.org/mailman/listinfo/python-list