当我尝试删除非空文件夹时,我收到"访问被拒绝"错误.我在尝试中使用了以下命令:os.remove("/folder_name")
.
删除/删除非空文件夹/目录的最有效方法是什么?
import shutil shutil.rmtree('/folder_name')
标准库参考:shutil.rmtree.
按照设计,rmtree
在包含只读文件的文件夹树上失败.如果要删除文件夹而不管它是否包含只读文件,请使用
shutil.rmtree('/folder_name', ignore_errors=True)
从Python文档上os.walk()
:
# 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
实例.不错,但可能不是最快的.
来自docs.python.org:
此示例显示如何在Windows上删除某些文件的只读位设置的目录树.它使用onerror回调清除readonly位并重新尝试删除.任何后续故障都会传播.
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)
import os import stat import shutil 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 shutil.rmtree(path, ignore_errors=False, onerror=errorRemoveReadonly)
如果设置了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,则会引发异常.请输入此处的代码
如果你确定,你想要删除整个目录树,并且对dir的内容不再感兴趣,那么爬行整个目录树就是愚蠢......只需从python调用本机OS命令就可以了.它将更快,更高效,更少内存消耗.
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])
根据kkubasik的回答,删除之前检查文件夹是否存在,更可靠
import shutil def remove_folder(path): # check if folder exists if os.path.exists(path): # remove if exists shutil.rmtree(path) else: # throw your exception to handle this special scenario raise XXError("your exception") remove_folder("/folder_name")
只需一些python 3.5选项即可完成上述答案.(我很想在这里找到它们).
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文件
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")