使用shutil复制图片时目标子目录变为二进制文件的问题求助
问题解决:按CSV指定复制图片到对应子文件夹
问题根源
- 目标目录不存在导致文件异常:当
test_path下的对应子文件夹未创建时,shutil.copy会将目标路径参数视为文件名,导致图片被重命名为无后缀的文件(看起来像无法使用的二进制文件)。 - 遍历逻辑冗余低效:原代码每处理一行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
相关产品推荐
相关产品推荐

