Wouldn't it be better to put this in a finally that covers the entire lifetime of f?  There are lines further down in this function that could also raise exceptions resulting in a dangling file handle.