Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when mkdir in multi threads in python

I have code in multi threads to create folder if not exists

if not os.path.exists(folder): os.makedirs(folder)

I got error like this

The folder cannot be created since a file already exists with the same path

I am not sure what can I do for this error, do you have any idea?

like image 605
mikezang Avatar asked Oct 16 '25 14:10

mikezang


1 Answers

Read the docs. If you don't care whether the directory already existed, just that it does when you're done, just call:

os.makedirs(folder, exist_ok=True)

Don't even check for the existence of the directory with exists (subject to race conditions), just call os.makedirs with exist_ok=True and it will create it if it doesn't exist and do nothing if it already exists.

This requires Python 3.2 or higher, but if you're on an earlier Python, you can achieve the same silent ignore with exception handling:

import errno

try:
    os.makedirs(folder)
except OSError as e:
    if e.errno != errno.EEXIST:
        raise  # Reraise if failed for reasons other than existing already
like image 86
ShadowRanger Avatar answered Oct 18 '25 05:10

ShadowRanger