How to read multiple files with error checking?

I have a function that reads multiple files. Like this:

    a = open("1.txt", "r")
    b = open("2.txt", "r")
    c = open("3.txt", "r")
except IOError:
    print("File {:s} failed".format(a, b or c))

I want that I can see which file failed during reading it. Can I somehow specify the IOError for specified file? I mean that if IOError appears in file a, do "command1", if in file b, do "command2" and so on?


The IOError exception is an alias of the OSError exception, which has a filename attribute. You can use that to switch behaviour based on the file that failed:

    a = open("1.txt", "r")
    b = open("2.txt", "r")
    c = open("3.txt", "r")
except OSError as error:
    print("File {:s} failed".format(error.filename))

I used the name OSError; IOError is deprecated and only kept around for backwards compatibility, see PEP 3151.


>>> try:
...     open('Nonesuch.txt')
... except OSError as error:
...     print('File {:s} failed'.format(error.filename))
File Nonesuch.txt failed

Note that it is the open() call that throws the exception, so no assignment has taken place. And because a file object can be referenced from multiple places, including from a list, there is no way to map a file object or filename back to the name you were going to assign it to. If you wanted to know which of a, b or c the file object would have been bound to, you'd have to create your own mapping:

filenames = {'1.txt': 'a', '2.txt': 'b', '3.txt': 'c'}
print("File {} failed".format(filenames[error.filename]))

Need Your Help

jQuery setTimeout

jquery settimeout

I'd like to add a timeout to this tooltip code so it only displays if the mouse hovers over it after a while rather than immediately... I tried adding the setTimeout() but I could not figure out ho...

Define JavaScript get and set function in object without using "this"?

javascript this jslint getter

I have a simple global object with a get and set function. JSlint is not liking that I am using "this" in the get and set function because it violates "use strict". What would I replace "this" wi...