You need to enable JavaScript to run this app. Python中是否有可无差别删除文件和目录的统一函数?
优惠活动
大模型
产品
解决方案
定价
更多

Python中是否有可无差别删除文件和目录的统一函数?

Python 等价于 rm -fr 的实现方案

Python标准库没有内置不需要判断目标类型的统一删除函数,需要自行简单封装,实现逻辑非常简单:

核心实现思路

  • 先判断路径是否存在,不存在直接返回(匹配rm -f忽略不存在目标的特性)
  • 如果是文件或符号链接,调用os.remove/Path.unlink删除
  • 如果是目录,调用shutil.rmtree递归删除目录下所有内容

代码示例

基础版本(仅实现核心功能)

import os
import shutil

def rm_rf(target_path: str) -> None:
    if not os.path.exists(target_path):
        return
    # 优先处理符号链接,避免跟随链接删除源文件
    if os.path.islink(target_path) or os.path.isfile(target_path):
        os.remove(target_path)
    elif os.path.isdir(target_path):
        shutil.rmtree(target_path)

静默版本(匹配rm -f忽略删除错误的特性)

如果不需要抛出删除异常(比如权限不足、文件被占用等场景),可以添加异常捕获:

import os
import shutil

def rm_rf(target_path: str) -> None:
    try:
        if os.path.islink(target_path) or os.path.isfile(target_path):
            os.remove(target_path)
        elif os.path.isdir(target_path):
            shutil.rmtree(target_path)
    except (FileNotFoundError, PermissionError, OSError):
        pass

基于 pathlib 的版本(Python 3.4+ 支持)

from pathlib import Path
import shutil

def rm_rf(target_path: str | Path) -> None:
    p = Path(target_path)
    if not p.exists():
        return
    if p.is_file() or p.is_symlink():
        p.unlink()
    else:
        shutil.rmtree(p)

注意事项

  • 封装时优先判断符号链接,可以避免误删符号链接指向的原始目录内容
  • 如果需要保留删除异常提示,去掉异常捕获块即可

内容的提问来源于stack exchange,提问作者Lolo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 00:36:14