Windows 上的 os.rename 引发 WindowsError 而不是 OSError
os.rename(src, dst)
... 在 Windows 上,如果 dst 已经存在,即使它是一个文件,也会引发 OSError ...
但是,对我来说,它会引发 WindowsError。文档中是否有错误?
问题的第二部分(更笼统,但受到上面提出的问题的启发):
UPD 很抱歉,问题的第二部分不正确。 WindowsError 确实被 except OSError
捕获,正如它应该的那样。
Python documentation says that
os.rename(src, dst)
... On Windows, if dst already exists, OSError will be raised even if it is a file ...
However, for me it raises WindowsError. Is there a mistake in the documentation?
The second part of the question (more general, but inspired by the problem formulated above):
UPD I am sorry, the second part of the question was incorrect. WindowsError is indeed catched by except OSError
as it should.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于 OSError 是 WindowsError 的超类,因此只需捕获 OSError 即可。
FWIW,核心开发人员可以自由地提出比文档承诺的最低限度更具体的异常。
另外,以下代码对我来说效果很好(Python2.7.2在WindowsXP上运行):
Since OSError is a superclass of WindowsError, just catch the OSError.
FWIW, the core devs are free to raise an exception more specific than the minimum promised by the docs.
Also, the following code works fine for me (Python2.7.2 running on WindowsXP):