Deleting read-only directory in Python

Solution 1:

shutil.rmtree can take an error-handling function that will be called when it has problem removing a file. You can use that to force the removal of the problematic file(s).

Inspired by http://mail.python.org/pipermail/tutor/2006-June/047551.html and http://techarttiki.blogspot.com/2008/08/read-only-windows-files-with-python.html:

import os
import stat
import shutil

def remove_readonly(func, path, excinfo):
    os.chmod(path, stat.S_IWRITE)
    func(path)

shutil.rmtree(top, onerror=remove_readonly)

(I haven't tested that snippet out, but it should be enough to get you started)

Solution 2:

If you import win32api from PyWin32, you can use:

win32api.SetFileAttributes(path, win32con.FILE_ATTRIBUTE_NORMAL)

To make files cease to be read-only.

Solution 3:

Another way is to define rmtree on Windows as

rmtree = lambda path: subprocess.check_call(['cmd', '/c', 'rd', '/s', '/q', path])