python - specifically handle file exists exception
Question: 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?](http://stackoverflow.com/questions/15032108/pythons-open-throws-
different-errors-for-file-not-found-how-to-handle-b). 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 ?


Answer: According to the code `print ...`, it seems like you're using Python 2.x.
[`FileExistsError`](http://docs.python.org/3/library/exceptions.html#FileExistsError)
was added in Python 3.3; You can't use `FileExistsError`.

Use
[`errno.EEXIST`](http://docs.python.org/2/library/errno.html#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
    

