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

后端 未结 7 1778
遥遥无期
遥遥无期 2020-12-06 05:12

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\")):
             


        
7条回答
  •  遥遥无期
    2020-12-06 05:25

    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.

提交回复
热议问题