How to avoid “WindowsError: [Error 5] Access is denied”

See RemoveDirectory documentation;
“The RemoveDirectory function marks a directory for deletion on close. Therefore, the directory is not removed until the last handle to the directory is closed.”

This means that if something manages to create a handle to the directory you remove (between creation and removal) then the directory isn’t actually removed and you get your ‘Access Denied’,

To solve this rename the directory you want to remove before removing it.

So

while True:
  mkdir('folder 1')
  rmdir('folder 1')

can fail, solve with;

while True:
  mkdir('folder 1')
  new_name = str(uuid4())
  rename('folder 1', new_name)
  rmdir(new_name)

Leave a Comment