【发布时间】:2013-12-26 20:01:27
【问题描述】:
我在这个论坛中遇到过一些示例,其中通过测试 OSError 中的 errno 值来处理文件和目录的特定错误(或者这些天是 IOError ?)。例如,这里的一些讨论 - Python's "open()" throws different errors for "file not found" - how to handle both exceptions?。但是,我认为,这不是正确的方法。毕竟,FileExistsError 的存在是为了避免担心errno。
以下尝试没有成功,因为我收到了令牌 FileExistsError 的错误。
try:
os.mkdir(folderPath)
except FileExistsError:
print 'Directory not created.'
您如何专门检查此错误和类似的其他错误?
【问题讨论】:
-
假设您使用 2.7,FileExistsError 在 Python 中不作为内置异常存在。在此处查看内置异常的完整列表:docs.python.org/2/library/exceptions.html#module-exceptions 在我看来,您应该为此使用“IOError”之类的内容。