Exceptions when closing a file

John Nagle nagle at animats.com
Tue Mar 20 14:29:46 EDT 2007


Ross Ridge wrote:
> Steven D'Aprano  <steve at REMOVE.THIS.cybersource.com.au> wrote:
> 
>>Closing a file can (I believe) raise an exception. Is that documented
>>anywhere? 
> 
> 
> In a catch-all statement for file objects: "When a file operation fails
> for an I/O-related reason, the exception IOError is raised."  The fact
> that close() is a file operation that might fail is revealed by "file
> objects are implemented using C's stdio package" and the fact the C's
> fclose() function can fail.
> 
> 
>>Is IOError the only exception it can raise?

     Closing a file that's being written can, of course, fail.
An I/O error is possible as the file is flushed to disk.

     This is useful; after the close has returned, you have
some confidence that the file has been fully written.

     If you want to force this error, write to a drive
reached over a network, or a removable medium like a floppy
or flash card.  Open a file for writing and disconnect the
network or remove the removable medium.

				John Nagle



More information about the Python-list mailing list