在 Python 中执行相当于 rm -rf
的最简单方法是什么?
原文由 Josh Gibson 发布,翻译遵循 CC BY-SA 4.0 许可协议
在 Python 中执行相当于 rm -rf
的最简单方法是什么?
原文由 Josh Gibson 发布,翻译遵循 CC BY-SA 4.0 许可协议
虽然有用,但 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 许可协议
2 回答5.2k 阅读✓ 已解决
2 回答1.1k 阅读✓ 已解决
4 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
2 回答864 阅读✓ 已解决
1 回答1.7k 阅读✓ 已解决