Python打开文件异常,我怎么知道详细的异常信息?

时间:2016-03-08 02:38:13

标签: python

代码评论中的问题。

try:
    with open('file1.txt', 'r') as f1:
        f1.read(...)

    with open('file2.txt', 'rb') as f2:
        f2.read(...)
        f2.write(...)

except IOError as e:
    # How do I know which file throwed the exception? So to report a friendly error message.
    # Further, can I know if the exception is caused by open, read, or write?

1 个答案:

答案 0 :(得分:0)

正如Ian所说,你可以尝试解析回溯以找出发生了什么错误以及在哪里。但是,使用两个try catch块会更容易:

try:
    with open('file1.txt', 'r') as f1:
        f1.read(...)

except IOError as e:
    # do something about error opening or reading f1

try:
    with open('file2.txt', 'rb') as f2:
        f2.read(...)
        f2.write(...)

except IOError as e:
    # do something about error opening/reading/writing f2