canonical file access pattern?

Hans-Joachim Widmaier hjwidmaier at web.de
Sat Dec 27 09:24:04 EST 2003


Recently, there was mentioned how someone who had understood Python's
error handling would write the "open and read file with error handling"
idiom. If I remember correctly, it went like this:

try:
    f = file(filename, op)
except IOError, e:
    # Handle exception
else:
    # Use the file
    f.close()

I don't think that's sufficient. First of all, opening a file is only
part of the job--reading and writing can go wrong too, and these are
not handled by the above code. Then I've seen OSError as well as IOError
raised occassionaly.

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

Is it really so wrong, then, to fold the read/write operations and close()
into the first try suite and handle all those errors in one go?
I'd just like to have a definitive pattern that I can stick to that is
considered bullet-proof.

Hans-Joachim Widmaier




More information about the Python-list mailing list