check if a directory is already created python

python, python-2.7

Solution

You could go for a try except:

try:
    os.mkdir(path,0755)
except OSError:
    pass 

“Easier to ask forgiveness than permission !”

Also this method is more safe that testing the directory before doing `mkdir`. Indeed, it is fairly possible that between the two os call implied by `ispath` and `mkdir` the directory may have been created or destroyed by another thread.

Problem

A very basic question, I have a module that creates directories on the fly, however, sometimes I want to put more than one file in a dir. If this happens, python rises an exception and says that the dir is already created, how can I avoid this and check if the dir is already created or not? The save module looks something like this: ``` def createdirs(realiz): # Create all the necessary directories path = "./doubDifferences_probandamp_realiz%d/"%realiz os.mkdir(path,0755) directory = os.path.split(path)[0] return directory ``` On the main program, I have this: ``` for realiz in range(1,1000): for i in range(dim): for j in range(i+1,i+4): ... dirspaths = mod_savefile.createdirs(realiz) ```

Original source