user2820579
user2820579

Reputation: 3461

check if a directory is already created python

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)

Upvotes: 3

Views: 211

Answers (3)

hivert
hivert

Reputation: 10667

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.

Upvotes: 7

Paul Seeb
Paul Seeb

Reputation: 6166

This should cover you. Just test if it is a directory before you try to create it.

if not os.path.isdir(path)
   os.mkdir(path,0755)

Upvotes: 3

Paulo Bu
Paulo Bu

Reputation: 29804

You have several ways. Either use os.path.isdir function:

import os.path 

def createdirs(realiz):
    # Create all the necessary directories
    path = "./doubDifferences_probandamp_realiz%d/"%realiz
    if not os.path.isdir(path):  # if not exists
        os.mkdir(path,0755)      # create it
    directory = os.path.split(path)[0]
    return directory

Or handle the exception.

Upvotes: 2

Related Questions