Are Python error numbers associated with IOError stable?

佐手、 提交于 2019-12-23 10:14:12

问题


I want to move a file, but in the case it is not found I should just ignore it. In all other cases the exception should be propagated. I have the following piece of Python code:

try:
    shutil.move(old_path, new_path)
except IOError as e:
    if e.errno != 2: raise e

errno == 2 is the one, that has 'No such file or directory' description. I wonder if this is stable across Python versions and platforms, and etc.


回答1:


It is better to use values from the errno module instead of hardcoding the value 2:

try:
    shutil.move(old_path, new_path)
except IOError as e:
    if e.errno != errno.ENOENT: raise e

This makes your code less likely to break in case the integer error value changes (although that is unlikely to occur).



来源:https://stackoverflow.com/questions/12283377/are-python-error-numbers-associated-with-ioerror-stable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!