如何删除/删除Python中不为空的文件夹?

当我尝试删除非空的文件夹时,出现“访问被拒绝”错误。 我在尝试中使用了以下命令: os.remove("/folder_name")

删除/删除非空的文件夹/目录最有效的方法是什么?

 import shutil shutil.rmtree('/folder_name') 

标准库参考:shutil.rmtree 。

os.walk() 的python文档 :

 # Delete everything reachable from the directory named in 'top', # assuming there are no symbolic links. # CAUTION: This is dangerous! For example, if top == '/', it # could delete all your disk files. import os for root, dirs, files in os.walk(top, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name)) 
 import shutil shutil.rmtree(dest, ignore_errors=True) 

从Python 3.4你可以使用:

 import pathlib def delete_folder(pth) : for sub in pth.iterdir() : if sub.is_dir() : delete_folder(sub) else : sub.unlink() pth.rmdir() # if you just want to delete dir content, remove this line 

其中pth是一个pathlib.Path实例。 不错,但可能不是最快的。

 shutil.rmtree(path,ignore_errors=False,onerror=errorRemoveReadonly) def errorRemoveReadonly(func, path, exc): excvalue = exc[1] if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES: # change the file to be readable,writable,executable: 0777 os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) # retry func(path) else: raiseenter code here 

如果设置了ignore_errors,则忽略错误; 否则,如果设置了onerror,则会调用它来处理带有参数(func,path,exc_info)的错误,其中func是os.listdir,os.remove或os.rmdir; path是导致它失败的那个函数的参数; 而exc_info是由sys.exc_info()返回的元组。 如果ignore_errors为false,onerror为None,则在此处引发exception

基于kkubasik的答案,检查文件夹是否存在删除之前,更强大

 import shutil def remove_folder(path): # check if folder exists if os.path.exists(path): # remove if exists shutil.rmtree(path) remove_folder("/folder_name") 

如果你确定,你想删除整个目录树,并没有更多的目录的内容感兴趣,然后爬整个目录树是愚蠢的…只是调用本地操作系统命令从python做到这一点。 这将更快,更有效,更less的内存消耗。

 RMDIR c:\blah /s /q 

或* nix

 rm -rf /home/whatever 

在Python中,代码看起来像..

 import sys import os mswindows = (sys.platform == "win32") def getstatusoutput(cmd): """Return (status, output) of executing cmd in a shell.""" if not mswindows: return commands.getstatusoutput(cmd) pipe = os.popen(cmd + ' 2>&1', 'r') text = pipe.read() sts = pipe.close() if sts is None: sts = 0 if text[-1:] == '\n': text = text[:-1] return sts, text def deleteDir(path): """deletes the path entirely""" if mswindows: cmd = "RMDIR "+ path +" /s /q" else: cmd = "rm -rf "+path result = getstatusoutput(cmd) if(result[0]!=0): raise RuntimeError(result[1]) 

从docs.python.org :

此示例显示如何在Windows上删除某些文件的只读位已设置的目录树。 它使用onerrorcallback清除只读位,并重新尝试删除。 任何后续的失败都会传播。

 import os, stat import shutil def remove_readonly(func, path, _): "Clear the readonly bit and reattempt the removal" os.chmod(path, stat.S_IWRITE) func(path) shutil.rmtree(directory, onerror=remove_readonly) 

只需要一些python 3.5选项来完成上面的答案。 (我会喜欢在这里find他们)。

 import os import shutil from send2trash import send2trash # (shutil delete permanently) 

删除文件夹如果为空

 root = r"C:\Users\Me\Desktop\test" for dir, subdirs, files in os.walk(root): if subdirs == [] and files == []: send2trash(dir) print(dir, ": folder removed") 

如果包含此文件,也删除此文件夹

  elif subdirs == [] and len(files) == 1: # if contains no sub folder and only 1 file if files[0]== "desktop.ini" or: send2trash(dir) print(dir, ": folder removed") else: print(dir) 

删除文件夹,如果它只包含.srt或.txt文件(S)

  elif subdirs == []: #if dir doesn't contains subdirectory ext = (".srt", ".txt") contains_other_ext=0 for file in files: if not file.endswith(ext): contains_other_ext=True if contains_other_ext== 0: send2trash(dir) print(dir, ": dir deleted") 

删除文件夹,如果其大小小于400kb:

 def get_tree_size(path): """Return total size of files in given path and subdirs.""" total = 0 for entry in os.scandir(path): if entry.is_dir(follow_symlinks=False): total += get_tree_size(entry.path) else: total += entry.stat(follow_symlinks=False).st_size return total for dir, subdirs, files in os.walk(root): If get_tree_size(dir) < 400000: # ≈ 400kb send2trash(dir) print(dir, "dir deleted") 

如果你不想使用shutil模块,你可以使用os模块。

 from os import listdir, rmdir, remove for i in listdir(directoryToRemove): os.remove(os.path.join(directoryToRemove, i)) rmdir(directoryToRemove) # Now the directory is empty of files 

要删除一个文件夹,即使它不存在(避免Charles Chow的答案中的竞争条件),但在其他事情出错时仍然有错误(例如,权限问题,磁盘读取错误,文件不是目录)

对于Python 3.x:

 import shutil def ignore_absent_file(func, path, exc_inf): except_instance = exc_inf[1] if isinstance(except_instance, FileNotFoundError): return raise except_instance shutil.rmtree(dir_to_delete, onerror=ignore_absent_file) 

Python 2.7代码几乎是一样的:

 import shutil import errno def ignore_absent_file(func, path, exc_inf): except_instance = exc_inf[1] if isinstance(except_instance, OSError) and \ except_instance.errno == errno.ENOENT: return raise except_instance shutil.rmtree(dir_to_delete, onerror=ignore_absent_file) 
 def deleteDir(dirPath): deleteFiles = [] deleteDirs = [] for root, dirs, files in os.walk(dirPath): for f in files: deleteFiles.append(os.path.join(root, f)) for d in dirs: deleteDirs.append(os.path.join(root, d)) for f in deleteFiles: os.remove(f) for d in deleteDirs: os.rmdir(d) os.rmdir(dirPath) 

您可以使用os.system命令来简化:

 import os os.system("rm -rf dirname") 

显然,它实际上是调用系统terminal来完成这个任务。