views:

420

answers:

4

shutil.rmtree will not delete read-only files on Windows. Is there a python equivalent of "rm -rf" ? Why oh why is this such a pain?

+1  A: 

There's a comment at the ActiveState site that says:

shutil.rmtree has its shortcomings. Although it is true you can use shutil.rmtree() in many cases, there are some cases where it does not work. For example, files that are marked read-only under Windows cannot be deleted by shutil.rmtree().

By importing the win32api and win32con modules from PyWin32 and adding line like "win32api.SetFileAttributes(path, win32con.FILE_ATTRIBUTE_NORMAL" to the rmgeneric() function, this obstacle can be overcome. I used this approach to fix the hot-backup.py script of Subversion 1.4 so it will work under Windows. Thank you for the recipe.

I don't use Windows so can't verify whether this works or not.

ire_and_curses
+1  A: 

If you import win32api from PyWin32, you can use:

win32api.SetFileAttributes(path, win32con.FILE_ATTRIBUTE_NORMAL)

To make files cease to be read-only.

Paul
+1  A: 

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, stat, shutil

def remove_readonly(fn, path, excinfo):
    if fn is os.rmdir:
        os.chmod(myFile, stat.S_IWRITE)
        os.rmdir(path)
    elif fn is os.remove:
        os.chmod(myFile, stat.S_IWRITE)
        os.remove(path)

shutil.rmtree(top, onerror=remove_readonly)

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

Steve Losh
+1  A: 

Here is a variant of what Steve posted, it uses the same basic mechanism, and this one is tested :-)

http://stackoverflow.com/questions/1213706/what-user-do-python-scripts-run-as-in-windows/1214935#1214935

ThomasH