python - specifically handle file exists exception

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)

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