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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With