سؤال

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

try:
    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:

try:
    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.

Demo:

>>> 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]))
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top