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

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


当前回答

import shutil

shutil.rmtree('/folder_name')

标准库参考:shutil.rmtree。

根据设计,rmtree在包含只读文件的文件夹树上失败。如果您希望删除文件夹而不管它是否包含只读文件,请使用

shutil.rmtree('/folder_name', ignore_errors=True)

其他回答

import shutil

shutil.rmtree('/folder_name')

标准库参考:shutil.rmtree。

根据设计,rmtree在包含只读文件的文件夹树上失败。如果您希望删除文件夹而不管它是否包含只读文件,请使用

shutil.rmtree('/folder_name', ignore_errors=True)

如果你不想使用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

从docs.python.org:

这个例子展示了如何在Windows中删除目录树 有些文件设置了只读位。它使用onerror 回调以清除只读位并重新尝试删除。任何 随后的失败将会传播。 导入os, stat 进口shutil Def remove_readonly(func, path, _) "清除只读位并重新尝试删除" 操作系统。chmod(路径,stat.S_IWRITE) func(路径) shutil。rmtree(目录,onerror = remove_readonly)

基于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")

对于Windows,如果目录不是空的,并且你有只读文件或者你会得到这样的错误

访问被拒绝 该进程无法访问该文件,因为它正被另一个进程使用

试试这个,os。system('rmdir /S /Q "{}"'.format(directory))

它相当于Linux/Mac中的rm -rf。