Windows 上的 os.rename 引发 WindowsError 而不是 OSError

发布于 2024-12-27 04:19:17 字数 420 浏览 2 评论 0原文

Python 文档说

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情绪操控生活 2025-01-03 04:19:17

由于 OSError 是 WindowsError 的超类,因此只需捕获 OSError 即可。

FWIW,核心开发人员可以自由地提出比文档承诺的最低限度更具体的异常。

另外,以下代码对我来说效果很好(Python2.7.2在WindowsXP上运行):

try:
    raise os.rename('nonexisting_file', 'def')
except OSError:
    print 'caught'

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):

try:
    raise os.rename('nonexisting_file', 'def')
except OSError:
    print 'caught'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文