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

8

26

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?

Zettazeugma answered 15/6, 2016 at 8:41 Comment(2)
check this: #12990612Flower
As I experienced, this error will be appeared if the directory is open and you run the the code and is related to removing process, not the creation step.Petra
A
15

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)
Arrhythmia answered 15/8, 2017 at 7:35 Comment(3)
Issue is no more actual, so I cannot check it. But I'm quite sure that this should workZettazeugma
I can confirm that this trick worked. Interestingly enough, after calling rmdir, I was using os.path.exists() to check whether the folder had been successfully deleted before attempting to recreate it. Even though os.path.exists(path) was returning False, I was still getting the 'Access is denied' error on running os.mkdir(path).Hasin
I also just saw what @Hasin reported. I thought I had this all handled with an os.path.exists() check in a loop until the folder didn't exist. Then one day I hit it even with that check. Extremely head-scratching...Livraison
S
9

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..."
She answered 27/3, 2017 at 12:39 Comment(2)
This is a good tip. Presumably if it works the vast majority of the time, then it's some transient issue, and just retrying is the right choice before failing out.Morehead
As written, you can't tell if you failed to rename. One fix (and to keep the raise traceback correct) is to except: if retry < 99: print('rename failed, retrying...' else: raiseCorry
K
7

What could cause this error?

You simply do not have access to the folder you are writing in for the process that is currently running (python.exe), or maybe even for the user. Unless your user is an admin there may be directories for which you do not have write permissions.


How can I avoid it?

In general to avoid such an exception, one would use a try and except block, in this case it would be an IOError. Therefore if you just want to overlook access denied and continue with the script you can try:

try:
    # 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")
except IOError:
    print("Error upon either deleting or creating the directory or files.")
else:
    print("Actions if file access was succesfull")
finally:
    print("This will be executed even if an exception of IOError was encountered")

If you truly were not expecting this error and it is not supposed to happen you have to change the permissions for the file. Depending on your user permissions there are various steps that you could take.

  • User that can execute programs as Admin: Option A

    1. Right-Click on cmd.exe.
    2. Click on Run as Administrator.
    3. Go to your script location via cd since it will be opened at C:\Windows\system32 unless you have edit certain parameters.
    4. Run your script > python myscript.py.
  • User that can execute programs as Admin: Option B

    1. Open file explorer.
    2. Go to the folder, or folders, you wish to write in.
    3. Right-Click on it.
    4. Select Properties.
    5. In the properties window select the security tab.
    6. Click Edit and edit it as you wish or need to give access to programs or users.
  • User with no Admin privileges:

    1. This probably means it is not your computer.
    2. Check for the PC help desk if at Uni or Work or ask your teacher if at School.
    3. If you are at home and it is your computer that means you have logged in with a non-admin user. The first one you create typically is by default. Check the user settings in the Control Panel if so.
    4. From there on the rest is pretty much the same afterwards.
Kist answered 15/6, 2016 at 9:37 Comment(3)
I tried everything on this answer but nothing worked, it's really bothering me.Klaxon
I am running into the same issue, and it is definitely not a permissions problem. If I put a few seconds of sleep between the rmtree and the mkdir it works every time, but if I do the mkdir immediately it fails every time.Hasin
Wow this question is old haha the thing is the original asker changed the question so much, my answer is basically just good for an overview on permission issues. The original question was just along the lines of not being able to access a folder without talking about exceptions but they actually wanted an answer were no exceptions were thrown so you are probably rightKist
C
3

For me it worked in this way:

while os.path.isdir (your_path):
    shutil.rmtree (your_path, ignore_errors=True)
os.makedirs (your_path)
Coenosarc answered 13/3, 2019 at 1:5 Comment(3)
I could run my code without any errors, but the directory has not been created successfully.Machiavellian
os.chdir("/") and os.makedirs(directory, access_rights) did the job for me!Machiavellian
This is the most elegant solution yet. Thanks.Roland
C
1

It happens because you are not checking if you have permissions to open that path. You need to change the permissions on those folders.

Canister answered 15/6, 2016 at 8:53 Comment(0)
S
1

Create your python script file. In this case you may copy it in C:\WINDOWS\system32. The script file is creating a folder named "Smaog"

import os
os.chdir('C:/Program Files')
os.makedirs('Smaog')

Create batch file, at any folder you like.

echo off
title Renaming Folder
python sample.py
pause

Save the batch file. To run it, right click and choose Run as Administrator

Though you may choose to do this instead if you don't want to put your python script in C:\WINDOWS\system32. In your batch file, indicate folder/directory where your python script file resides.

echo off
title Renaming Folder
cd c:\Users\Smaog\Desktop
python sample.py
pause

Then run it as Administrator as explained just above.

Starfish answered 6/2, 2018 at 13:13 Comment(0)
C
1

I had this problem last night after switching Py2 to Py3 and realized that I was installing it for all users. That means you are installg it into Program Files directory not instead of the %AppData%. Mostly running as administrator solves the problem as some of you said above but I use VSCode and sometimes PyCharm and love to use the terminal in them. Even if you try to run these programs as an administator you have lots of annoying times when trying to focus on your lovely code.

My Solution :
1 ) Full uninstall (including Py Launcher)
2 ) Then install with custom install with the provided installer BUT ...
3 ) DO NOT choose the INSTALL FOR ALL USERS option.

I think that will make your day much more easy without any "[Error 5]" lines at your command prompt as it worked for me.

Creepy answered 17/6, 2018 at 22:54 Comment(0)
A
1

os.chmod() is one approach in python through which we can change the mode of path to the numeric mode similar to chmod 777 in linux.

Syntax: os.chmod(filepath, mode)

import os
import stat
# In Windows 
os.chmod(file_name, stat.S_IRWXU|stat.S_IRWXG|stat.S_IRWXO)
# In Linux
os.chmod(file_name, 0o555)
Anhydrite answered 27/7, 2022 at 5:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.