Windows error 5: Access is denied when trying delete a directory in windows

两盒软妹~` 提交于 2019-11-29 15:40:20

问题


i am trying to delete a directory but when i run the code it gives windows error 5: access is denied. here is my code: in the Release folder, there is a folder called OD.

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

the error is like:

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

回答1:


This was due to the file permissions issue.

You need to have the permissions to perform that task on that file.

To get the permissions associated with a file, useos.stat(fileName)

You can explicitly check the write permission for that file using os.access(fileName, os.W_OK)

Then, to change the permission, os.chmod(fileName,permissionNumeric).

Ex: os.chmod(fileName, '0777')

To change the permission for the current file that is being executed, use os.chmod(__file__, '0777')




回答2:


I use pydev. And my solution is:

  1. Stop Eclipse.
  2. Start Eclipse with option Run as administrator



回答3:


takeown /F C:\<dir> /R /A
icacls C:\<dir> /grant administrators:F /t

Give ownership to administrators and give full control to administrators, if your user is an administrator.




回答4:


in order to change files located in "C:" you must have admin privileges, you can either get them before starting the script or while doing so, for instance:

#!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, )

code taken from: How to run python script with elevated privilege on windows

script by: Gary Lee



来源:https://stackoverflow.com/questions/16183934/windows-error-5-access-is-denied-when-trying-delete-a-directory-in-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!