40

shutil.rmtree不会删除 Windows 上的只读文件。是否有相当于“rm -rf”的python?为什么哦,为什么这么痛苦?

4

6 回答 6

61

shutil.rmtree可以采用错误处理函数,当删除文件出现问题时将调用该函数。您可以使用它来强制删除有问题的文件。

灵感来自http://mail.python.org/pipermail/tutor/2006-June/047551.htmlhttp://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)

(我还没有测试过那个片段,但它应该足以让你开始)

于 2009-12-11T17:41:23.187 回答
4

如果你从 PyWin32 导入 win32api,你可以使用:

win32api.SetFileAttributes(path, win32con.FILE_ATTRIBUTE_NORMAL)

使文件不再是只读的。

于 2009-12-11T17:34:38.537 回答
4

另一种方法是将 Windows 上的 rmtree 定义为

rmtree = lambda path: subprocess.check_call(['cmd', '/c', 'rd', '/s', '/q', path])
于 2014-09-12T15:49:52.000 回答
4

这可能会随着Python 3.5的发布(目前 - 2015 年 6 月 - 仍在开发中)得到修复,因为在文档中对此给出了提示。

您可以在此处找到错误报告。这是相应的变更集

请参阅Python 3.5 文档中新添加的示例:

import os, stat
import shutil

def remove_readonly(func, path, _):
    "Clear the readonly bit and reattempt the removal"
    os.chmod(path, stat.S_IWRITE)
    func(path)

shutil.rmtree(directory, onerror=remove_readonly)
于 2015-01-21T16:39:48.383 回答
3

ActiveState网站上有一条评论说:

shutil.rmtree 有它的缺点。尽管在许多情况下您可以使用 shutil.rmtree() ,但在某些情况下它不起作用。例如,在 Windows 下标记为只读的文件无法通过 shutil.rmtree() 删除。

通过从 PyWin32 中导入 win32api 和 win32con 模块并在 rmgeneric() 函数中添加“win32api.SetFileAttributes(path, win32con.FILE_ATTRIBUTE_NORMAL”之类的行,就可以克服这个障碍。我使用这种方法修复了 hot-backup.py 脚本Subversion 1.4 所以它可以在 Windows 下工作。谢谢你的食谱。

我不使用 Windows,所以无法验证这是否有效。

于 2009-12-11T17:34:30.187 回答
2

这是史蒂夫发布的一种变体,它使用相同的基本机制,并且已经过测试:-)

python脚本在Windows中运行的用户是什么?

于 2009-12-11T22:26:01.080 回答