30

I have come across examples in this forum where a specific error around files and directories is handled by testing the errno value in OSError (or IOError these days ?). For example, some discussion here - Python's "open()" throws different errors for "file not found" - how to handle both exceptions?. But, I think, that is not the right way. After all, a FileExistsError exists specifically to avoid having to worry about errno.

The following attempt didn't work as I get an error for the token FileExistsError.

try:
    os.mkdir(folderPath)
except FileExistsError:
    print 'Directory not created.'

How do you check for this and similar other errors specifically ?

Community
  • 1
  • 1
cogitoergosum
  • 2,309
  • 4
  • 38
  • 62
  • 2
    Assuming you use 2.7, FileExistsError does not exist as a built-in exception in Python. See a full list of built-in exceptions here: http://docs.python.org/2/library/exceptions.html#module-exceptions It looks to me like you should use something like "IOError" for this. – Dyrborg Dec 26 '13 at 20:10

2 Answers2

48

According to the code print ..., it seems like you're using Python 2.x. FileExistsError was added in Python 3.3; You can't use FileExistsError.

Use errno.EEXIST:

import os
import errno

try:
    os.mkdir(folderPath)
except OSError as e:
    if e.errno == errno.EEXIST:
        print('Directory not created.')
    else:
        raise
falsetru
  • 357,413
  • 63
  • 732
  • 636
3

Here's an example of dealing with a race condition when trying to atomically overwrite an existing symlink:

# os.symlink requires that the target does NOT exist.
# Avoid race condition of file creation between mktemp and symlink:
while True:
    temp_pathname = tempfile.mktemp()
    try:
        os.symlink(target, temp_pathname)
        break  # Success, exit loop
    except FileExistsError:
        time.sleep(0.001)  # Prevent high load in pathological conditions
    except:
        raise
os.replace(temp_pathname, link_name)
Tom Hale
  • 40,825
  • 36
  • 187
  • 242