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

基于images_id数组用Python迁移指定图片遇文件不存在错误求助

问题分析与解决

从报错信息看,核心问题是源文件路径错误:生成的源路径出现了重复的img_align_celeba文件夹(如/content/train/img_align_celeba/img_align_celeba/058713.jpg),导致系统找不到对应文件。

错误原因

  • 要么是images_folder变量的取值本身包含重复路径(比如误设为/content/train/img_align_celeba/img_align_celeba/);
  • 要么是new_id数组里的元素不是纯文件名(比如包含img_align_celeba/058713.jpg这类带路径的格式)。

修正后的代码

先确认两个前提:

  • images_folder是图片所在的根文件夹路径,正确值应为/content/train/img_align_celeba/;
  • new_id数组中的每个元素都是纯文件名(如058713.jpg)。

使用以下代码实现迁移:

import os
import shutil

def move_selected_images(images_folder, new_id_list, dest_folder):
    # 确保目标文件夹存在,不存在则自动创建
    os.makedirs(dest_folder, exist_ok=True)
    
    for img_id in new_id_list:
        # 用os.path.join正确拼接路径,避免手动拼接的错误
        src_path = os.path.join(images_folder, img_id)
        dest_path = os.path.join(dest_folder, img_id)
        
        # 检查源文件是否存在,避免报错中断程序
        if not os.path.exists(src_path):
            print(f"跳过不存在的文件: {src_path}")
            continue
        
        # 若目标文件已存在,先删除(可根据需求调整此逻辑)
        if os.path.exists(dest_path):
            os.remove(dest_path)
        
        # 执行文件移动
        shutil.move(src_path, dest_path)

# 替换为你的实际路径和数组
images_folder = "/content/train/img_align_celeba/"
destination_folder = "/content/train/image/"
move_selected_images(images_folder, new_id, destination_folder)

关键优化点

  • 用os.path.join拼接路径,自动适配不同系统的路径分隔符,彻底避免手动拼接导致的重复路径或分隔符错误;
  • os.makedirs(..., exist_ok=True)替代手动判断文件夹是否存在,代码更简洁;
  • 增加源文件存在性检查,跳过不存在的文件并打印提示,避免程序意外中断;
  • 使用shutil.move统一处理文件移动,兼容性更强(支持跨文件系统移动)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 21:00:54