【问题标题】:Windows error 5: Access is denied when trying delete a directory in windowsWindows 错误 5:尝试在 Windows 中删除目录时拒绝访问
【发布时间】:2013-04-17 12:41:11
【问题描述】:

我正在尝试删除一个目录,但是当我运行代码时,它给出了 Windows 错误 5:访问被拒绝。这是我的代码:在 Release 文件夹中,有一个名为 OD 的文件夹。

if os.path.exists(os.path.join(get_path_for_output,'Release')):
        shutil.rmtree(os.path.join(get_path_for_output,'Release')) 

错误是这样的:

WindowsError: [Error 5] Access is denied: 'C:\\Users\\marahama\\Desktop\\Abdur_Release\\Release\\OD\\automations\\GEM\\FMS_adapter.py'

【问题讨论】:

  • 有人在某处使用该文件。也许这与您正在运行的文件相同?
  • 没有。我想。我已经检查过了。
  • 关闭所有程序和cmd提示窗口再试一次,有文件锁了。
  • 是的。问题已解决。该文件处于只读模式。
  • 有可能,当您打开该文件夹然后应用 rmtree 命令时。意思是,你打开了那个文件夹。

标签: python-2.7 windowserror


【解决方案1】:

要更改位于“C:”中的文件,您必须具有管理员权限, 您可以在启动脚本之前或同时获取它们,例如:

#!python
# coding: utf-8
import sys
import ctypes

def run_as_admin(argv=None, debug=False):
    shell32 = ctypes.windll.shell32
    if argv is None and shell32.IsUserAnAdmin():
        return True

    if argv is None:
        argv = sys.argv
    if hasattr(sys, '_MEIPASS'):
        # Support pyinstaller wrapped program.
        arguments = map(unicode, argv[1:])
    else:
        arguments = map(unicode, argv)
    argument_line = u' '.join(arguments)
    executable = unicode(sys.executable)
    if debug:
        print 'Command line: ', executable, argument_line
    ret = shell32.ShellExecuteW(None, u"runas", executable, argument_line, None, 1)
    if int(ret) <= 32:
        return False
    return None


if __name__ == '__main__':
    ret = run_as_admin()
    if ret is True:
        print 'I have admin privilege.'
        raw_input('Press ENTER to exit.')
    elif ret is None:
        print 'I am elevating to admin privilege.'
        raw_input('Press ENTER to exit.')
    else:
        print 'Error(ret=%d): cannot elevate privilege.' % (ret, )

代码取自:How to run python script with elevated privilege on windows

脚本作者:Gary Lee

【讨论】:

    【解决方案2】:

    这是由于文件权限问题。

    您需要拥有对该文件执行该任务的权限。

    要获取与文件关联的权限,请使用os.stat(fileName)

    您可以使用os.access(fileName, os.W_OK) 明确检查该文件的写入权限

    然后,要更改权限,os.chmod(fileName,permissionNumeric)

    例如:os.chmod(fileName, '0777')

    要更改正在执行的当前文件的权限, 使用os.chmod(__file__, '0777')

    【讨论】:

    • 我得到了 TypeError: an integer is required 并将 '0777' 更改为 0777 为我工作。
    【解决方案3】:

    我使用 pydev。我的解决方案是:

    1. 停止 Eclipse。
    2. 使用选项以管理员身份运行启动 Eclipse

    【讨论】:

      【解决方案4】:
      takeown /F C:\<dir> /R /A
      icacls C:\<dir> /grant administrators:F /t
      

      如果您的用户是管理员,则将所有权授予管理员并将完全控制权授予管理员。

      【讨论】:

        猜你喜欢
        • 2019-01-14
        • 2011-04-06
        • 2011-05-15
        • 2011-09-09
        • 1970-01-01
        • 2016-04-05
        • 2018-12-09
        • 1970-01-01
        • 2020-11-17
        相关资源
        最近更新 更多