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

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


当前回答

您可以尝试下面的代码删除文件或文件夹,而不管它们是空的还是非空的。

import shutil
import os

directory = "path/to/the/root/folder"
files_in_directory = os.listdir(directory)

for file in files_in_directory:
    try:
        path_to_file_or_folder = os.path.join(directory, file)
        shutil.rmtree(path_to_file_or_folder)
    except:
        os.unlink(path_to_file_or_folder)

其他回答

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

import os


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

基于递归的纯pathlib解决方案:

from pathlib import Path

def remove_path(path: Path):
    if path.is_file() or path.is_symlink():
        path.unlink()
        return
    for p in path.iterdir():
        remove_path(p)
    path.rmdir()

支持Windows和符号链接

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)

十年后,在使用Python 3.7和Linux时,仍然有不同的方法来做到这一点:

import subprocess
from pathlib import Path

#using pathlib.Path
path = Path('/path/to/your/dir')
subprocess.run(["rm", "-rf", str(path)])

#using strings
path = "/path/to/your/dir"
subprocess.run(["rm", "-rf", path])

本质上,它使用Python的子进程模块来运行bash脚本$ rm -rf '/path/to/your/dir,就像使用终端来完成相同的任务一样。它不是完全的Python,但它完成了。

我加入pathlib的原因。路径示例是因为根据我的经验,它在处理许多路径变化时非常有用。导入pathlib的额外步骤。路径模块和将最终结果转换为字符串通常是一个较低的成本,我的开发时间。如果Path.rmdir()带有一个arg选项来显式地处理非空dirs,那就很方便了。

从docs.python.org:

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