递归删除目录及符号链接时shutil.rmtree报FileNotFoundError如何解决
shutil.rmtree删除含无效软链接目录报错的解决方法
该报错的核心原因是
shutil.rmtree默认行为和shell命令rm -Rf $DIR并不完全等价:当待删除目录中存在指向不存在路径的无效符号链接时,shutil.rmtree遍历文件时会抛出FileNotFoundError,而rm -Rf会直接忽略这类无效软链接、仅删除链接本身。
通用适配方案(Python 3.3+)
通过自定义错误回调仅过滤文件不存在的异常,不屏蔽权限不足等其他真实报错:
import shutil import os from os.path import exists def ignore_not_found_error(func, path, exc_info): # 仅忽略文件不存在类的错误,其余异常正常抛出 if isinstance(exc_info[1], FileNotFoundError): return raise exc_info[1] path_dir = "你的目标目录路径" if exists(path_dir): shutil.rmtree(path_dir, onerror=ignore_not_found_error)
简化方案(Python 3.12+)
Python 3.12 版本的shutil.rmtree新增了更易用的异常处理参数,可以直接简化写法,同时指定不跟随符号链接,完全对齐rm -Rf的行为:
import shutil from os.path import exists def handle_exc(func, path, exc): if not isinstance(exc, FileNotFoundError): raise exc path_dir = "你的目标目录路径" if exists(path_dir): shutil.rmtree( path_dir, follow_symlinks=False, # 不跟进软链接删除指向的源文件,仅删除软链接本身 onexc=handle_exc )
补充说明
- 不推荐直接使用
shutil.rmtree(path_dir, ignore_errors=True),该参数会屏蔽所有报错,包括权限不足、磁盘只读等真实运行异常,不利于问题排查。 - 问题复现逻辑和你描述的一致:在待删除目录中执行
ln -s /不存在的源路径 ./软链接名创建无效软链接后,调用默认参数的shutil.rmtree就会触发对应报错。
内容的提问来源于stack exchange,提问作者Jürgen K.
相关产品推荐
相关产品推荐

