1

I'm trying to handle IOError generated when trying to open a non existent file. I do:

try:
    inputFile = open('nosuchfile', 'r')
except IOError as exception:
    print 'error: %s' % (exception)

This gives me:

error: [Errno 2] No such file or directory: 'nosuchfile'

But I'm only interested in the message and not the [Errno 2] part. So I change my code.

print 'error: %s' % (exception.strerror)

But now I get:

error: No such file or directory

Where did the name of the file go? I know I could just print the file name separately, but I would really like how (if at all) the name was stored in the exception, but not in either of its arguments (printing exception.errno gives 2).

I am using version 2.7.3.

1 Answer 1

5

The filename is stored in, well, the filename property:

try:
    inputFile = open('nosuchfile', 'r')
except IOError as exception:
    print ('error: %s: %r' % (exception.strerror, exception.filename))
Sign up to request clarification or add additional context in comments.

6 Comments

Oh got it. But why is this not revealed when I print exception.args?
NB: exception.strerror is not an Exception attribute
@Mr_and_Mrs_D Well, it does work, so why do you think it wouldn't be an attribute?
It is an IOError attribute - not an Exception attribute - apparently one must call str(exception)
@Mr_and_Mrs_D str(exception) is the whole message including the filename, which is not being asked for. strerror is just the core error string. And of course strerror and filename are only available in IOError exception objects. But that's not a problem here, since we only catch IOError in the first place.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.