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

使用shutil拷贝文件时,找不到os.listdir已列出的存在文件

问题原因及解决方法

错误根源

os.listdir(path) 返回的仅仅是文件名(比如Z4554545.jpg),而非文件的完整路径。当你直接调用shutil.copy(file, dst_dir)时,程序会在Jupyter Notebook的当前工作目录下查找该文件,而非你指定的C:/Users/images文件夹,因此才会出现文件不存在的报错。

修正后的代码

你需要将文件名与原路径拼接成完整的源文件路径,再传入shutil.copy:

import os
import shutil

path = r'C:/Users/images'
dst_dir = r'C:/Users/images/new'

# 确保目标目录存在,避免因目录未创建报错
os.makedirs(dst_dir, exist_ok=True)

for file in os.listdir(path):
    # 拼接得到源文件的完整路径
    src_full_path = os.path.join(path, file)
    # 额外判断:确保当前项是文件(避免误复制子目录)
    if os.path.isfile(src_full_path):
        if file in id_final2 or file in id_final:
            shutil.copy(src_full_path, dst_dir)

额外优化说明

  • os.makedirs(dst_dir, exist_ok=True)可以确保目标目录存在,即便目录已存在也不会抛出错误。
  • 增加os.path.isfile(src_full_path)判断,能避免把path下的子目录当成文件复制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 17:06:26