来自 Python document :
For backwards compatibility, if three arguments are passed, the args attribute contains only a 2-tuple of the first two constructor arguments.
那么我们如何处理第三个参数,例如“无效路径”?
try:
open('invalid path')
except OSError as e:
error = e
print(error.args[0],error.args[1])
print(e)
结果:
2 No such file or directory
[Errno 2] No such file or directory: 'invalid path'
请您参考如下方法:
来自相同的文档:
For exceptions that involve a file system path (such as open() or os.unlink()), filename is the file name passed to the function. For functions that involve two file system paths (such as os.rename()), filename2 corresponds to the second file name passed to the function.
所以你只需执行 error.filename,因为 filename 是一个可选的 arg,它只针对特定类型的错误传递。
要进行一劳永逸的检查,您可以使用hasattr:
if hasattr(error, 'filename'):
print(error.filename)
