5

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.

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
Anton Daneyko
  • 6,528
  • 5
  • 31
  • 59

1 Answers1

7

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

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
  • 4
    "unlikely" is an understatement - the number of programs that would break is mind boggling, it will *never* happen. But using a symbol rather than a magic number is always preferred. – Mark Ransom Sep 05 '12 at 14:16
  • Thanks a lot. I did not even know, such a module exists. This is exactly what I wanted. – Anton Daneyko Sep 05 '12 at 15:17