Easiest way to rm -rf in Python
在python中使用等效的
1 2 | import shutil shutil.rmtree("dir-you-want-to-remove") |
虽然rmtree很有用,但它不是等价的:如果您试图删除一个文件,它会出错,而
为了解决这个问题,您需要检查您的路径是文件还是目录,并相应地采取行动。像这样的方法应该可以做到:
1 2 3 4 5 6 7 8 | 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) |
注意:此功能不处理字符或块设备(需要使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | $ 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的评论注意限制
1 2 3 4 5 6 7 8 9 10 | 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模块)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | def delite(filepath): 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) |
Windows阻止删除文件的解决方法是截断文件:
1 2 3 4 | outputFile = open(r"filename.txt","w") outputFile.truncate() outputFile.close() outputFile = open(r"filename.txt","a+") |
来源:https://stackoverflow.com/a/2769090/6345724
shutil.rmtree()是正确的答案,但只需看看另一个有用的函数-os.walk()。
只要这样做:
1 2 3 | import os dirname ="path_to_directory_to_remove" os.system("rm -rf %s" % dirname) |