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

TuTan :

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?

John Gander :

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)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

PyLint raises 'misplaced-bare-raise' in error handler function for shutil.rmtree(...)

Will shutil.rmtree() check for the root directory?

How do I force mkdir to overwrite existing directory?

shutil.rmtree() clarification

shutil.rmtree() clarification

shutil.rmtree fails on Windows with 'Access is denied'

Permission denied @ dir_s_mkdir Error

npm install: Error: EACCES: permission denied, mkdir

Access denied error when trying to save file to directory

Python mocking not working for shutil.rmtree

OS call gives permission denied

mkdir: cannot create directory 'example': Permission denied

os.mkdir() returns error "FileNotFoundError: [Errno 2] No such file or directory"

os.mkdir can fail with PermissionError after successful shutil.rmtree on Windows

Is os.remove()+os.rmdir() better then shutil.rmtree()

shutil.rmtree to remove files only?

python shutil.rmtree throwing errors

Creating a symlink gives cannot overwrite directory error

Sudo mkdir fails due to permission denied error

RHC setup gives mkdir error

mkdir error: no such file or directory

ansible 2.0.0.2 - shutil.rmtree error but the playbook success

How to rename IIS website directory with Powershell (Access denied error)

FreeIPA to Active Directory trust not working:Access denied error

Codeigniter mkdir: Permission denied error

python - remove directory and subfolders with shutil.rmtree - str object not callable

vscode installed in other directory gives access denied error

Runs sometimes and sometimes gives an index error

" No such file or directory" error when calling `os.mkdir` on WSL