Python中最简单的方法是rm -rf

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

 import shutil shutil.rmtree("dir-you-want-to-remove") 

虽然有用,但是rmtree不是等价的:如果你试图删除一个单独的文件, rm -f不会(见下面的例子)。

为了解决这个问题,你需要检查你的path是一个文件还是一个目录,并相应地执行。 像这样的事情应该做的伎俩:

 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之间的差异的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的评论注释限制

shutil.rmtree()是正确的答案,但只是看看另一个有用的function – os.walk()

 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) 

加布里埃尔格兰特的版本略有改善。 这也适用于目录的符号链接。 注意:函数不处理Un * x字符和块设备(它需要使用stat模块)。

def delite(文件path):

 import os, stat, sys def intertwin(_list): list1 = [] for i in _list: list1 += i return list1 allpath = os.walk(filepath) walk = [] dirs = [] path = [] allfiles = [] for i in allpath: walk.append(i) for i in walk: dirs.append(i[0]) for _dir in dirs: os.chdir(_dir) files = os.listdir(_dir) files1 = [] for i in files: files1.append(_dir + '\\' + i) files = files1[:] allfiles.append(files) allfiles = intertwin(allfiles) for i in allfiles: os.chmod(i, stat.S_IRWXU) allfiles.reverse() os.chdir(sys.path[0]) for i in allfiles: try: os.remove(i) except: try: os.rmdir(i) except: pass os.chmod(filepath, stat.S_IRWXU) try: os.remove(filepath) except: os.rmdir(filepath) allfiles.reverse() os.chdir(sys.path[0]) for i in allfiles: try: os.remove(i) except: try: os.rmdir(i) except: pass os.chmod(filepath, stat.S_IRWXU) try: os.remove(filepath) except: os.rmdir(filepath) 

只要这样做:

 import os dirname = "path_to_directory_to_remove" os.system("rm -rf %s" % dirname)