canonical file access pattern?

Rene Pijlman reply.in.the.newsgroup at my.address.is.invalid
Tue Dec 30 06:00:52 EST 2003


Hans-Joachim Widmaier:
>Then I've seen OSError as well as IOError raised occassionaly.

The documentation says only IOError can be raised. Is there a bug?

"When a file operation fails for an I/O-related reason, the exception
IOError is raised."
http://www.python.org/doc/current/lib/bltin-file-objects.html

>Seems like I have do this, then:
>
>try:
>    f = file(filename, op)
>except (OSError, IOError), e:
>    # Handle open() error
>else:
>    try:
>        # read/write to the file
>        f.close()         # flushes write buffers, so can fail, too
>    except (OSError, IOError), e:
>        # Handle read/write errors

This is not correct, since the file is not closed when an exception is
thrown by read or write.

If we assume the following:
1. A file that is opened should be closed in all cases
2. Every exception raised by read, write or close should be caught and
handled

Then this would need to be the algorithm:

try:
    f = file("spam.txt", "w")
except IOError, e:
    # Handle open() error
    pass
else:
    try:
        try:
            # read/write to the file
            pass
        except IOError, e:
            # Handle read/write errors
            pass
    finally:
        try:
            f.close()
        except IOError, e:
            # Handle close error
            pass

Not very pretty, but I can't think of a simplification that does not
violate one of the assumptions.

-- 
René Pijlman




More information about the Python-list mailing list