且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python的"open()"对于“找不到文件",抛出不同的错误. -如何处理两种例外情况?

更新时间:2023-11-22 15:04:34

在3.3中, IOError成为OSError 的别名,而FileNotFoundErrorOSError的子类.所以你可以尝试

except (OSError, IOError) as e:
   ...

这将产生一个相当大的净值,并且如果不检查e.errno,您不能假定该异常是未找到文件",但它可能涵盖了您的用例.

PEP 3151 详细讨论了更改的理由.>

I have a script where a user is prompted to type a filename (of a file that is to be opened), and if the file doesn't exist in the current directory, the user is prompted again. Here is the short version:

file = input("Type filename: ")

...
try:
    fileContent = open(filename, "r")
    ...
except FileNotFoundError:
    ...

When I tested my script on my MacOS X in Python 3.3x it worked perfectly fine when I type the wrong filename on purpose (it executes the suite under "expect").

However, when I wanted to run my code on a Windows computer in Python 3.2x, I get an error that says that "FileNotFoundError" is not defined. So, Python 3.2 on Windows thinks "FileNotFoundError" is a variable and the programs quits with an error.

I figured out that Python 3.2 on Windows throws an "IOError" if the input filename is not valid. I tested it on my Linux machine in Python 2.7, and it's also an IOError.

My problem is now, that the code with

except "FileNotFoundError":

won't run on Windows's Python 3.2, but if I change it to

except "IOError":

it won't work on my Mac anymore.

How could I work around it? The only way I can think of is to use just except, which I usually don't want.

In 3.3, IOError became an alias for OSError, and FileNotFoundError is a subclass of OSError. So you might try

except (OSError, IOError) as e:
   ...

This will cast a pretty wide net, and you can't assume that the exception is "file not found" without inspecting e.errno, but it may cover your use case.

PEP 3151 discusses the rationale for the change in detail.