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

使用shutil复制图片时目标子目录变为二进制文件的问题求助

问题解决:按CSV指定复制图片到对应子文件夹

问题根源

  1. 目标目录不存在导致文件异常:当test_path下的对应子文件夹未创建时,shutil.copy会将目标路径参数视为文件名,导致图片被重命名为无后缀的文件(看起来像无法使用的二进制文件)。
  2. 遍历逻辑冗余低效:原代码每处理一行CSV数据就遍历所有源目录和文件,重复操作浪费大量资源。

修正代码

import os
import csv
import shutil

source = '/Users/turuud/Desktop/TUT/Dscience_exp/Images/'
testcsv = '/Users/turuud/Desktop/TUT/Dscience_exp/sample_submission.csv'
test_path = '/Users/turuud/Desktop/TUT/Dscience_exp/test/'
# 第二组文件的目标路径,根据需求修改
train_path = '/Users/turuud/Desktop/TUT/Dscience_exp/train/'

# 读取CSV中所有需归入第一组的文件名,存入集合提升查询效率
target_test_files = set()
with open(testcsv, 'r') as file:
    csvreader = csv.reader(file)
    next(csvreader)  # 跳过表头
    for row in csvreader:
        target_test_files.add(row[0])

# 遍历源目录下的所有子文件夹
for directory in os.listdir(source):
    source_dir = os.path.join(source, directory)
    if not os.path.isdir(source_dir):
        continue  # 跳过非目录文件
    
    # 创建第一组的目标子文件夹(不存在则自动创建)
    test_target_dir = os.path.join(test_path, directory)
    os.makedirs(test_target_dir, exist_ok=True)
    # 创建第二组的目标子文件夹(不存在则自动创建)
    train_target_dir = os.path.join(train_path, directory)
    os.makedirs(train_target_dir, exist_ok=True)
    
    # 遍历当前源子文件夹中的图片,按规则分配到两组
    for img_file in os.listdir(source_dir):
        source_file = os.path.join(source_dir, img_file)
        if img_file in target_test_files:
            shutil.copy(source_file, os.path.join(test_target_dir, img_file))
        else:
            shutil.copy(source_file, os.path.join(train_target_dir, img_file))

关键修改说明

  • 确保目标目录存在:使用os.makedirs(..., exist_ok=True)自动创建所需的子文件夹,避免因目录缺失导致的文件异常。
  • 优化查询效率:将CSV中的目标文件名存入集合,查询操作从O(n)降为O(1),大幅提升处理速度。
  • 一次性完成分组:遍历一次源目录即可完成两组文件的分类复制,逻辑更简洁高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 15:25:15