Jos*_*son 71
import shutil
shutil.rmtree("dir-you-want-to-remove")
Run Code Online (Sandbox Code Playgroud)
Gab*_*ant 35
虽然有用,但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)
Run Code Online (Sandbox Code Playgroud)
注意:此函数不会处理字符或块设备(需要使用该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'
Run Code Online (Sandbox Code Playgroud)
编辑:处理符号链接; 请注意@ pevik评论的限制
import os
import shutil
def rm_r(path):
if not os.path.exists(path):
return
if os.path.isfile(path) or os.path.islink(path):
os.unlink(path)
else:
shutil.rmtree(path)
Run Code Online (Sandbox Code Playgroud)
稍微改进了加布里埃尔·格兰特的版本。这也适用于目录的符号链接。
注意:函数不处理Un*x 字符和块设备(需要使用stat模块)。