Python "FileExists" error when making directory Python "FileExists" error when making directory python python

Python "FileExists" error when making directory


As of Python >=3.2, os.makedirs() can take a third optional argument exist_ok:

os.makedirs(mydir, exist_ok=True)


Any time code can execute between when you check something and when you act on it, you will have a race condition. One way to avoid this (and the usual way in Python) is to just try and then handle the exception

while True:    mydir = next_dir_name()    try:        os.makedirs(mydir)        break    except OSError, e:        if e.errno != errno.EEXIST:            raise           # time.sleep might help here        pass

If you have a lot of threads trying to make a predictable series of directories this will still raise a lot of exceptions, but you will get there in the end. Better to just have one thread creating the dirs in that case


Catch the exception and, if the errno is 17, ignore it. That's the only thing you can do if there's a race condition between the isdir and makedirs calls.

However, it could also be possible that a file with the same name exists - in that case os.path.exists would return True but os.path.isdir returns false.