Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make an error verifiy with os.makedirs in Python?

Tags:

python

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 ?

like image 317
Bruno 'Shady' Avatar asked Mar 05 '10 00:03

Bruno 'Shady'


2 Answers

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
like image 109
nosklo Avatar answered Oct 01 '22 13:10

nosklo


In Python3.2 and above, just add exist_ok=True will solve this problem.

If exist_ok is False (the default), an FileExistsError is raised if the target directory already exists.

os.makedirs('C:\\test\\',exist_ok=True)
like image 38
showteth Avatar answered Oct 01 '22 13:10

showteth