我在这个论坛中遇到过一些示例,其中通过测试 OSError
(或 IOError
这些天?)。例如,这里的一些讨论 - Python's "open()" throws different errors for "file not found" - how to handle both exceptions? .但是,我认为,这不是正确的方法。毕竟,FileExistsError
的存在是为了避免担心 errno
。
以下尝试无效,因为我收到 token FileExistsError
错误。
try:
os.mkdir(folderPath)
except FileExistsError:
print 'Directory not created.'
您如何专门检查此错误和类似的其他错误?
最佳答案
根据代码 print ...
,您似乎使用的是 Python 2.x。 FileExistsError
在 Python 3.3 中添加;你不能使用 FileExistsError
。
使用 errno.EEXIST
:
import os
import errno
try:
os.mkdir(folderPath)
except OSError as e:
if e.errno == errno.EEXIST:
print('Directory not created.')
else:
raise
关于python - 专门处理文件存在异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20790580/