close

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

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error How to avoid “WindowsError: [Error 5] Access is denied” in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

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

Today I get the following error How to avoid “WindowsError: [Error 5] Access is denied” in python.

How To Solve avoid “WindowsError: [Error 5] Access is denied” Error ?

  1. How To Solve avoid “WindowsError: [Error 5] Access is denied” Error ?

    To Solve avoid “WindowsError: [Error 5] Access is denied” Error To solve this rename the directory you want to remove before removing it.

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

    To Solve avoid “WindowsError: [Error 5] Access is denied” Error To solve this rename the directory you want to remove before removing it.

Solution 1

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)

Solution 2

Permissions might be the problem, but I had the same problem ‘[Error 5] Access is denied’ on a os.rename() and a simple retry-loop was able to rename the file after a few retries.

for retry in range(100):
    try:
        os.rename(src_name,dest_name)
        break
    except:
        print "rename failed, retrying..."

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read