关于python:shutil.rmtree删除只读文件

shutil.rmtree to remove readonly files

我想在Python中使用shutil.rmtree删除目录。有问题的目录包含.git控制目录,该目录git标记为只读和隐藏。

只读标志导致rmtree失败。在Powershell中,我可以执行" del -force "来强制删除只读标志。 Python中是否有等效功能?我真的不想遍历整棵树两次,但是rmtree的onerror参数似乎没有重试该操作,因此我不能使用

1
2
3
4
def set_rw(operation, name, exc):
    os.chmod(name, stat.S_IWRITE)

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


经过更多调查后,以下内容似乎起作用:

1
2
3
4
def del_rw(action, name, exc):
    os.chmod(name, stat.S_IWRITE)
    os.remove(name)
shutil.rmtree(path, onerror=del_rw)

换句话说,实际上是在onerror函数中删除该文件。 (在这种情况下,您可能需要检查onerror处理程序中的目录并使用rmdir-我并不需要它,但这可能只是我的问题所特有的。