Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwrite directory with shutil.rmtree and os.mkdir sometimes gives 'Access is denied' error

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?

like image 823
TuTan Avatar asked Apr 13 '18 04:04

TuTan


2 Answers

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)
like image 179
John Gander Avatar answered Oct 11 '22 19:10

John Gander


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

like image 42
M T Avatar answered Oct 11 '22 18:10

M T