Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

There's the script to re-create folder:

# Remove folder (if exists) with all files
if os.path.isdir(str(os.path.realpath('..') + "\\my_folder")):
        shutil.rmtree(os.path.realpath('..') + "\\my_folder", ignore_errors=True)
# Create new folder
os.mkdir(os.path.realpath('..') + "\\my_folder")

This works nearly always, but in some cases (on creation step) I get

WindowsError: [Error 5] Access is denied: 'C:\\Path\\To\\my_folder'

What could cause this error and how can I avoid it?

like image 237
Andersson Avatar asked Jun 15 '16 08:06

Andersson


People also ask

How do I fix access denied in Python?

The PermissionError: [errno 13] permission denied error occurs when you try to access a file from Python without having the necessary permissions. To fix this error, use the chmod or chown command to change the permissions of the file so that the right user and/or group can access the file.


2 Answers

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) 
like image 54
owillebo Avatar answered Oct 18 '22 00:10

owillebo


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..."
like image 23
ebmoll Avatar answered Oct 18 '22 00:10

ebmoll