shutil.rmtree fails on Windows with 'Access is denied' [duplicate] shutil.rmtree fails on Windows with 'Access is denied' [duplicate] python python

shutil.rmtree fails on Windows with 'Access is denied' [duplicate]


Check this question out: What user do python scripts run as in windows?

Apparently the answer is to change the file/folder to not be read-only and then remove it.

Here's onerror() handler from pathutils.py mentioned by @Sridhar Ratnakumar in comments:

def onerror(func, path, exc_info):    """    Error handler for ``shutil.rmtree``.    If the error is due to an access error (read only file)    it attempts to add write permission and then retries.    If the error is for another reason it re-raises the error.        Usage : ``shutil.rmtree(path, onerror=onerror)``    """    import stat    # Is the error an access error?    if not os.access(path, os.W_OK):        os.chmod(path, stat.S_IWUSR)        func(path)    else:        raise


I'd say implement your own rmtree with os.walk that ensures access by using os.chmod on each file before trying to delete it.

Something like this (untested):

import osimport statdef rmtree(top):    for root, dirs, files in os.walk(top, topdown=False):        for name in files:            filename = os.path.join(root, name)            os.chmod(filename, stat.S_IWUSR)            os.remove(filename)        for name in dirs:            os.rmdir(os.path.join(root, name))    os.rmdir(top)      


Well, the marked solution did not work for me... did this instead:

os.system('rmdir /S /Q "{}"'.format(directory))