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

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


当前回答

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

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

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

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

其他回答

删除一个文件夹,即使它可能不存在(避免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)

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

在我的情况下,删除的唯一方法是使用所有的可能性,因为我的代码应该运行cmd.exe或powershell.exe。如果是你的情况,只需要用下面的代码创建一个函数就可以了:

        #!/usr/bin/env python3

        import shutil
        from os import path, system
        import sys

        # Try to delete the folder ---------------------------------------------
        if (path.isdir(folder)):
            shutil.rmtree(folder, ignore_errors=True)

        if (path.isdir(folder)):
            try:
                system("rd -r {0}".format(folder))
            except Exception as e:
                print("WARN: Failed to delete => {0}".format(e),file=sys.stderr)

        if (path.isdir(self.backup_folder_wrk)):
            try:
                system("rd /s /q {0}".format(folder))
            except Exception as e:
                print("WARN: Failed to delete => {0}".format(e),file=sys.stderr)

        if (path.isdir(folder)):
            print("WARN: Failed to delete {0}".format(folder),file=sys.stderr)
        # -------------------------------------------------------------------------------------

它有助于删除包含所有文件和文件夹的目录

import os


def rrmdir(path):
    for entry in os.scandir(path):
        if entry.is_dir():
            rrmdir(entry)
        else:
            os.remove(entry)
    os.rmdir(path)