tags:

views:

114

answers:

2

How can I make a verify error for this command?

if blablablabla:
    os.makedirs('C:\\test\\')

If the folder already exists, he return me an error... how can I make it ignore this error? and move on ?

+5  A: 
try:
    os.makedirs('C:\\test\\')
except OSError:
    pass

You also might want to check the specific "already exists" error (since OSError could mean other things, like permission denied...

import errno
try:
    os.makedirs('C:\\test\\')
except OSError as e:
    if e.errno != errno.EEXIST:
        raise  # raises the error again
nosklo
note that `except OSError as e` is python 2.6+ specific syntax. For python <2.6 use `except OSError, e`.
nosklo
You should *always* check the reason in cases like this. If the dir already exists it's probably ok, but if there is a permission problem or disk full etc. you need to give the user an error
gnibbler
what if there is `EnvironmentError` ?
ghostdog74
@ghostdog74 : then it will be raised as normal, stopping the program, as expected. What else would you want?
nosklo
`os.makedirs()` might make other types of errors. If you are going to catch only `OSError` , how about the rest? That's what i am asking.
ghostdog74
ghostdog74: If an error you did not anticipate was raised, it should not be caught, it should be raised as normal and stop the program, because your program is inconsistent. Then you fix the program with your new knowledge. This is the only way to do it right, if you silence errors you won't even know about them happening.
kaizer.se
@ghostdog74 : the only error you know how to handle is if the directory already exists. You handle that by ignoring the error, because you wanted to create the directory in the first place, and it already exists so you don't have to do anything else. Any other error that happens, you don't know how to handle, so you let them fly instead of hiding them.
nosklo
A: 

you can try/except?

try:
   os.makedirs('C:\\test\\')
except: pass
ghostdog74
bare try-except (without specifying the exception) is a bad practice and should be avoided, since it could hide errors you don't want to hide, like `KeyboardInterrupt` or `MemoryError`... Always catch the exact error you're trying to handle.
nosklo
In 2.5 onwards KeyboadInterrupt etc all comes from BaseException. Further, OP just want to ignore errors...
ghostdog74
That doesn't matter, a naked except clause cahces any exceptions whatsoever. What is important in the original question is how to ignore the right exception, absolutely not ignoring all exceptions.
kaizer.se