惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

J
Java Code Geeks
量子位
腾讯CDC
A
About on SuperTechFans
小众软件
小众软件
Microsoft Azure Blog
Microsoft Azure Blog
T
Tailwind CSS Blog
V
V2EX
B
Blog RSS Feed
H
Hackread – Cybersecurity News, Data Breaches, AI and More
GbyAI
GbyAI
Recent Announcements
Recent Announcements
Microsoft Security Blog
Microsoft Security Blog
博客园 - 叶小钗
罗磊的独立博客
宝玉的分享
宝玉的分享
WordPress大学
WordPress大学
大猫的无限游戏
大猫的无限游戏
IT之家
IT之家
V
Visual Studio Blog
D
DataBreaches.Net
博客园 - 三生石上(FineUI控件)
月光博客
月光博客
有赞技术团队
有赞技术团队

博客园 - androllen

Python yield 关键词 PDF 构成 桌面客户端的主要类型和技术方案 Python 压缩转义 数据结构 二叉树遍历 数据结构 线性表 JS 字符串转换为函数体 VSCode 配置内部Python项目 缺少模块ModuleNotFoundError C# 基础知识 算法-数列 算法-排序算法 C# 设计模式-简单工厂模式 C# 设计模式 C# Utils .Net 异步与同步 WPF StreamGeometry Vue 打开窗口输出文件路径 CSS Flexbox layout 2 CSS Flexbox layout 1
异步删除嵌套文件夹及文件
androllen · 2025-04-03 · via 博客园 - androllen
import os
import shutil
import asyncio
import aiofiles.os as aio_os
from typing import List

async def rm_with_chmod(func, path, exc_info):
    """修改权限后重试删除"""
    import stat
    os.chmod(path, stat.S_IWRITE)
    func(path)

async def rm_file(filepath: str, hold_dir: bool = True):
    """异步删除文件或文件夹
    参数:
    filepath: 文件路径
    hold_dir: 如果是删除目录,是否保留目录,默认保留
    """
    if not await aio_os.path.exists(filepath):
        return

    if await aio_os.path.isfile(filepath):
        print(f"delete file: {filepath}")
        await aio_os.remove(filepath)
        return

    if not hold_dir:
        print(f"delete dir: {filepath}")
        await aio_os.rmtree(filepath, onerror=rm_with_chmod)
        return

    children = await aio_os.listdir(filepath)
    for child in children:
        child_path = os.path.join(filepath, child)
        await rm_file(child_path, False)

async def collect_paths(filepath: str) -> List[str]:
    """收集所有文件和文件夹路径"""
    paths = []
    if await aio_os.path.isfile(filepath):
        paths.append(filepath)
    else:
        paths.append(filepath)
        children = await aio_os.listdir(filepath)
        for child in children:
            child_path = os.path.join(filepath, child)
            paths.extend(await collect_paths(child_path))
    return paths

def binary_search_delete(paths: List[str]):
    """使用二分查找确定删除顺序"""
    # 按路径长度排序,确保先删除子文件和子文件夹
    paths.sort(key=lambda x: len(x), reverse=True)
    return paths

async def async_delete(filepath: str, hold_dir: bool = True):
    """异步删除入口函数"""
    # 1. 收集所有路径
    paths = await collect_paths(filepath)
    # 2. 使用二分查找确定删除顺序
    paths = binary_search_delete(paths)
    # 3. 异步删除
    for path in paths:
        await rm_file(path, hold_dir)

# 示例用法
async def main():
    target_path = "path/to/your/file_or_directory"
    await async_delete(target_path, hold_dir=False)

# 运行异步任务
if __name__ == "__main__":
    asyncio.run(main())

需要安装 pip install aiofiles
https://zh.zliby.ru/book/31851703/863582/高等数学工本2023年版.html?dsource=recommend