Paul Moore Paul Moore - 5 months ago 66
Python Question

shutil.rmtree to remove readonly files

I want to use

in Python to remove a directory. The directory in question contains a
control directory, which git marks as read-only and hidden.

The read-only flag causes
to fail. In Powershell, I would do "del -force" to force removal of the read-only flag. Is there an equivalent in Python? I'd really rather not walk the whole tree twice, but the
argument to rmtree doesn't seem to retry the operation, so I can't use

def set_rw(operation, name, exc):
os.chmod(name, stat.S_IWRITE)

shutil.rmtree('path', onerror=set_rw)


After more investigation, the following appears to work:

def del_rw(action, name, exc):
    os.chmod(name, stat.S_IWRITE)
shutil.rmtree(path, onerror=del_rw)

In other words, actually remove the file in the onerror function. (You might need to check for a directory in the onerror handler and use rmdir in that case - I didn't need that but it may just be something specific about my problem.