异步删除嵌套文件夹及文件
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

浙公网安备 33010602011771号