pythonpython-3.xshutil

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?


Solution

  • 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)