You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中shutil.move偶发FileNotFoundError问题排查求助

问题分析与解决方案

错误定位

从异常信息来看,FileNotFoundError提示的是找不到指定路径,箭头左侧是源文件路径temp/image_0.png,右侧是目标路径C:\\Users\\math-milan\\Desktop\\src/downloads/#0012c-name_of_image.png。结合你提到的“源文件夹中的图片会被删除”,大概率是目标路径的父目录不存在,或是存在竞态条件导致源文件在移动操作执行前被移除。

可能的原因

  • 路径拼接不规范:直接用字符串拼接路径f"{self._temp_path}/{filename}",在Windows系统下可能因为分隔符(/和\)的兼容性问题,偶尔导致路径解析错误,系统找不到源文件。
  • 目标父目录缺失:目标路径的父文件夹(比如C:\\Users\\math-milan\\Desktop\\src/downloads/)可能未创建成功,或是被意外删除,导致无法写入目标文件。
  • 竞态条件:在os.listdir遍历到文件后、shutil.move执行前,源文件被其他进程/线程(比如程序其他逻辑、系统清理工具)删除。
  • 目标文件占用:如果目标文件已存在且被其他进程锁定,也可能触发类似错误,但错误信息通常会有差异。

解决建议

  • 规范路径拼接:改用系统原生路径拼接方法,避免分隔符问题:
    src_path = os.path.join(self._temp_path, filename)
    target_path = f"{self._image.path}.png"
    shutil.move(src_path, target_path)
    # 或者用pathlib更简洁
    from pathlib import Path
    src_path = Path(self._temp_path) / filename
    target_path = Path(f"{self._image.path}.png")
    shutil.move(src_path, target_path)
    
  • 确保目标父目录存在:在移动文件前,先创建目标路径的父目录(如果不存在):
    target_path = f"{self._image.path}.png"
    os.makedirs(os.path.dirname(target_path), exist_ok=True)
    
  • 增加存在性检查与重试机制:针对偶尔出现的瞬时问题,添加检查和重试:
    import time
    src_path = os.path.join(self._temp_path, filename)
    target_path = f"{self._image.path}.png"
    max_retries = 3
    for _ in range(max_retries):
        if os.path.exists(src_path):
            try:
                os.makedirs(os.path.dirname(target_path), exist_ok=True)
                shutil.move(src_path, target_path)
                break
            except FileNotFoundError:
                time.sleep(0.1)
        else:
            # 源文件已不存在,记录日志或跳过
            break
    
  • 排查竞态条件:检查是否有其他代码逻辑、外部进程在操作temp文件夹,避免在遍历后删除源文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 10:58:29