My code:
if os.path.exists(myDir):
shutil.rmtree(myDir)
os.mkdir(myDir)
Problem: It always work if myDir does not exist. If myDir exists, sometimes it throws error, sometimes it works.
Error log:
os.mkdir(myDir)
PermissionError: [WinError 5] Access is denied: 'myDir'
My guess: when I call os.mkdir, sometimes shutil.rmtree hasn't finished execution/ hasn't released the permission for the directory. Hence, the error.
Is there any way to ensure complete execution of shutil.rmtree before calling os.mkdir?
So I encountered the same issue. What I have been using is a pause after shutil.rmtree
. I think that pretty much anything that causes your computer to use a clock cycle would do.
All code:
import os
import shutil
import time
dataDir = 'C:/Data/'
if os.path.exists(TEMPDIR):
shutil.rmtree(TEMPDIR)
time.sleep(.0000000000000001)
os.makedirs(TEMPDIR)
If at first you don't succeed...
if os.path.exists(report_path):
shutil.rmtree(report_path)
while True:
try:
os.mkdir(report_path)
break
except PermissionError:
print('Damned Win 10 PERMISSION exception, trying again')
continue
...and if that doesn't work there is at least <ctrl> -c
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