I disagree with the other answers that mention the union of try / except / finally blocks. This would change the behavior since you would not want the finally block to try to close the file if the failure failed. The split blocks are correct here (although it is better to use the new syntax < with open(filename,'rU') as f ).
There are reasons why read () may fail. For example, the data may be too large to fit in memory, or the user could signal an interrupt with the -C control. These cases will not be caught by an IOError, but they will be handled (or not) by the caller, who may want to do different things depending on the nature of the application. However, the code still has an obligation to clear the file, even if it does not deal with the error, therefore, finally, with no exceptions.
Brian source share