Python的"open()"对于“找不到文件",抛出不同的错误. -如何处理两种例外情况? [英] Python's "open()" throws different errors for "file not found" - how to handle both exceptions?
问题描述
我有一个脚本,其中提示用户键入文件名(即将打开的文件的文件名),如果当前目录中不存在该文件,则会再次提示用户.这是简短的版本:
file = input("Type filename: ")
...
try:
fileContent = open(filename, "r")
...
except FileNotFoundError:
...
当我在Python 3.3x的MacOS X上测试脚本时,当我有意输入错误的文件名时,它工作得很好(它在期望"下执行套件).
但是,当我想运行我的代码时 在Python 3.2x的Windows计算机上,出现错误,提示未定义"FileNotFoundError".因此,Windows上的Python 3.2认为"FileNotFoundError"是变量,并且程序因错误退出.
我发现,如果输入文件名无效,Windows上的Python 3.2会抛出"IOError".我在Python 2.7的Linux机器上对其进行了测试,它也是IOError.
我的问题是,带有
的代码except "FileNotFoundError":
无法在Windows的Python 3.2上运行,但是如果我将其更改为
except "IOError":
它将不再在我的Mac上运行.
我该如何解决?我能想到的唯一方法就是使用
except
,我通常不想要.
在3.3中, IOError
成为OSError
的别名,而FileNotFoundError
是OSError
的子类.所以你可以尝试
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.
这篇关于Python的"open()"对于“找不到文件",抛出不同的错误. -如何处理两种例外情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!