Python 如何避免“WindowsError: [错误 5] 访问被拒绝”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37830326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:59:02  来源:igfitidea点击:

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

pythonpython-2.7windowserror

提问by Andersson

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?

什么可能导致此错误,我该如何避免?

回答by ebmoll

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.

权限可能是问题所在,但我在 a 上遇到了同样的问题“[错误 5] 访问被拒绝”,os.rename()并且一个简单的重试循环能够在几次重试后重命名文件。

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

回答by owillebo

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."

请参阅 RemoveDirectory 文档;“RemoveDirectory 函数在关闭时标记要删除的目录。因此,在目录的最后一个句柄关闭之前,不会删除该目录。”

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)

回答by Mixone

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.

您根本无权访问您正在为当前正在运行的进程 (python.exe) 写入的文件夹,甚至可能无法访问用户。除非您的用户是管理员,否则您可能没有写入权限的目录。



How can I avoid it?

我怎样才能避免它?

In general to avoid such an exception, one would use a tryand exceptblock, 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:

一般来说,为了避免这种异常,人们会使用 atryexcept块,在这种情况下它会是一个IOError。因此,如果您只想忽略拒绝访问并继续执行脚本,您可以尝试:

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 cdsince it will be opened at C:\Windows\system32unless 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.
  • 可以以管理员身份执行程序的用户:选项 A

    1. 右键单击cmd.exe
    2. 单击以管理员身份运行
    3. 转到您的脚本位置 viacd因为C:\Windows\system32除非您编辑了某些参数,否则它将被打开。
    4. 运行您的脚本> python myscript.py
  • 可以以管理员身份执行程序的用户:选项 B

    1. 打开文件资源管理器。
    2. 转到要写入的文件夹或文件夹。
    3. 右键单击它。
    4. 选择属性。
    5. 在属性窗口中选择安全选项卡。
    6. 单击“编辑”并根据您的意愿或需要对其进行编辑以授予程序或用户的访问权限。
  • 没有管理员权限的用户:

    1. 这可能意味着它不是您的计算机。
    2. 如果在大学或工作,请查看电脑帮助台,如果在学校,请询问您的老师。
    3. 如果您在家并且是您的计算机,则意味着您已使用非管理员用户登录。您创建的第一个通常是默认的。如果是,请检查控制面板中的用户设置。
    4. 之后的其余部分几乎相同。

回答by Sav

For me it worked in this way:

对我来说,它以这种方式工作:

while os.path.isdir (your_path):
    shutil.rmtree (your_path, ignore_errors=True)
os.makedirs (your_path)

回答by wind85

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

发生这种情况是因为您没有检查您是否有权打开该路径。您需要更改这些文件夹的权限。

回答by AdrianMY

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"

创建你的 python 脚本文件。在这种情况下,您可以将其复制到 C:\WINDOWS\system32 中。脚本文件正在创建一个名为“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.

如果您不想将 Python 脚本放在 C:\WINDOWS\system32 中,您可以选择这样做。在您的批处理文件中,指明您的 python 脚本文件所在的文件夹/目录。

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

Then run it as Administrator as explained just above.

然后按照上面的说明以管理员身份运行它。

回答by Mesut U?ar

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 Filesdirectory 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.

我昨晚在将 Py2 切换到 Py3 后遇到了这个问题,并意识到我正在为所有用户安装它。这意味着您将它安装到Program Files目录而不是%AppData%。大多数以管理员身份运行可以解决上面一些人所说的问题,但我使用 VSCode,有时使用 PyCharm 并且喜欢在其中使用终端。即使您尝试以管理员身份运行这些程序,在尝试专注于您可爱的代码时也会遇到很多烦人的时间。

My Solution :
1 ) Full uninstall (including Py Launcher)
2 ) Then install with custom installwith the provided installer BUT ...
3 ) DO NOTchoose the INSTALL FOR ALL USERSoption.

我的解决方案:
1)完全卸载(包括Py Launcher
2)然后使用提供的安装程序进行自定义安装,但......
3)不要选择为所有用户安装选项。

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

我认为这会让你的一天更轻松,因为它对我有用,命令提示符下没有任何“[错误 5]”行。