Python 的“open()”为“找不到文件”抛出不同的错误——如何处理这两种异常?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15032108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python's "open()" throws different errors for "file not found" - how to handle both exceptions?
提问by
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").
当我在我的 MacOS X 上用 Python 3.3x 测试我的脚本时,当我故意输入错误的文件名时,它运行得非常好(它在“期望”下执行套件)。
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.
但是,当我想在使用 Python 3.2x 的 Windows 计算机上运行我的代码时,我收到一条错误消息,指出未定义“FileNotFoundError”。因此,Windows 上的 Python 3.2 认为“FileNotFoundError”是一个变量,程序会因错误而退出。
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.
我发现如果输入文件名无效,Windows 上的 Python 3.2 会抛出“IOError”。我在我的 Linux 机器上用 Python 2.7 测试过,它也是一个 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
不会在 Windows 的 Python 3.2 上运行,但如果我将其更改为
except "IOError":
it won't work on my Mac anymore.
它不再适用于我的 Mac。
How could I work around it? The only way I can think of is to use just
except, which I usually don't want.
我该如何解决它?我能想到的唯一方法是使用 just
except,我通常不想要。
采纳答案by Russell Borogove
In 3.3, IOErrorbecame an alias for OSError, and FileNotFoundErroris a subclass of OSError. So you might try
在 3.3 中,IOError成为 的别名OSError,FileNotFoundError是 的子类OSError。所以你可以试试
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.
这将投下一个相当广泛的网络,您不能在不检查的e.errno情况下假设异常是“找不到文件” ,但它可能涵盖您的用例。
PEP 3151discusses the rationale for the change in detail.
PEP 3151详细讨论了更改的基本原理。
回答by dm03514
you can catch 2 errors at the same time
您可以同时捕获 2 个错误
except (FileNotFoundError, IOError):
except (FileNotFoundError, IOError):
I didn't realize that is what you were asking. I hope there is a more eloquent solution then to manually inspect
我没有意识到这就是你要问的。我希望有一个更雄辩的解决方案然后手动检查
try:
error_to_catch = FileNotFoundError
except NameError:
error_to_catch = IOError
except error_to_catch
except error_to_catch
cwallenpoole does this conditional more eloquently in his answer
(error_to_catch = getattr(__builtins__,'FileNotFoundError', IOError))
cwallenpoole 在他的回答中更雄辩地做到了这一点
(error_to_catch = getattr(__builtins__,'FileNotFoundError', IOError))
回答by cwallenpoole
This strikes me as better than a simple except:, but I'm not sure if it is the best solution:
这比简单的更好except:,但我不确定它是否是最好的解决方案:
error_to_catch = getattr(__builtins__,'FileNotFoundError', IOError)
try:
f = open('.....')
except error_to_catch:
print('!')
回答by Alex Che
So to exactly catch only when a file is not found, I do:
因此,只有在找不到文件时才能准确捕获,我这样做:
import errno
try:
open(filename, 'r')
except (OSError, IOError) as e: # FileNotFoundError does not exist on Python < 3.3
if getattr(e, 'errno', 0) == errno.ENOENT:
... # file not found
raise

