在 Python 中执行 rm -rf 的最简单方法

新手上路,请多包涵

在 Python 中执行相当于 rm -rf 的最简单方法是什么?

原文由 Josh Gibson 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.6k
2 个回答
import shutil
shutil.rmtree("dir-you-want-to-remove")

原文由 Josh Gibson 发布,翻译遵循 CC BY-SA 2.5 许可协议

虽然有用,但 rmtree 并不等同:如果您尝试删除单个文件,它会出错,而 rm -f 不会(请参见下面的示例)。

要解决这个问题,您需要检查您的路径是文件还是目录,并采取相应的措施。这样的事情应该可以解决问题:

 import os
import shutil

def rm_r(path):
    if os.path.isdir(path) and not os.path.islink(path):
        shutil.rmtree(path)
    elif os.path.exists(path):
        os.remove(path)

注意:此函数不会处理字符或块设备(需要使用 stat 模块)。

rm -f 和Python的 shutils.rmtree 之间的差异示例

$ mkdir rmtest
$ cd rmtest/
$ echo "stuff" > myfile
$ ls
myfile
$ rm -rf myfile
$ ls
$ echo "stuff" > myfile
$ ls
myfile
$ python
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import shutil
>>> shutil.rmtree('myfile')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/shutil.py", line 236, in rmtree
    onerror(os.listdir, path, sys.exc_info())
  File "/usr/lib/python2.7/shutil.py", line 234, in rmtree
    names = os.listdir(path)
OSError: [Errno 20] Not a directory: 'myfile'

编辑: 处理符号链接;根据@pevik 的评论注意限制

原文由 Gabriel Grant 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题