Syntax to catch specific exceptions ?

Fredrik Lundh fredrik at pythonware.com
Sun Mar 10 16:46:42 EST 2002


Pekka Niiranen wrote:
> I can get the error text and number as follows, but how to catch only
> "File exists" OSError ?
>
> try:
> ...  os.mkdir('e:\\tmp')
> except OSError, (errno, strerror):
> ...  print strerror
> ...
> File exists

catch it, check the errno attribute, and raise it again
if it's not the right error:

import os, errno

try:
    os.mkdir(somedir)
except OSError, v:
    if v.errno != errno.EEXIST:
        raise
    # directory exists

alternatively, you can use os.path.isdir to check if the
directory exists before you call mkdir.

</F>

<!-- (the eff-bot guide to) the python standard library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->





More information about the Python-list mailing list