Colab自动创建多级目录:解决CIFAR10分类图片存储报错问题
解决Colab中保存图片时目录不存在的问题
报错[Errno 2] No such file or directory的核心原因是你要保存文件的多级目录尚未创建,Python默认不会自动生成缺失的父目录。可以通过以下两种自动化方式解决:
方法1:使用os.makedirs
导入os模块,在保存图片前调用os.makedirs创建目标目录,通过exist_ok=True参数避免目录已存在时抛出异常。
修改后的适配代码:
import os from PIL import Image import numpy as np # CIFAR10官方标签列表 cifar10_labels = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'] for i in range(len(test_images)): original_image = Image.fromarray((test_images[i]*255).astype(np.uint8)) saliency_image = Image.fromarray((absoluteGradientBatch[i]*255).astype(np.uint8)) # 动态生成路径参数 label_name = cifar10_labels[test_labels[i]] pred_status = 'correct' if predictions[i] == test_labels[i] else 'incorrect' image_index = str(i) # 构建基础存储路径 base_path = f'/content/drive/MyDrive/pictures/{label_name}/{pred_status}/{image_index}' # 自动创建所有缺失的多级目录 os.makedirs(base_path, exist_ok=True) # 保存图片 original_image.save(os.path.join(base_path, 'original.jpeg')) saliency_image.save(os.path.join(base_path, 'saliency.jpeg'))
方法2:使用pathlib(推荐,更简洁的路径处理)
Python 3.4+内置的pathlib模块提供了面向对象的路径操作,代码可读性更强:
from pathlib import Path from PIL import Image import numpy as np cifar10_labels = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'] for i in range(len(test_images)): original_image = Image.fromarray((test_images[i]*255).astype(np.uint8)) saliency_image = Image.fromarray((absoluteGradientBatch[i]*255).astype(np.uint8)) label_name = cifar10_labels[test_labels[i]] pred_status = 'correct' if predictions[i] == test_labels[i] else 'incorrect' image_index = str(i) # 用Path对象构建层级路径 base_path = Path('/content/drive/MyDrive/pictures') / label_name / pred_status / image_index # 自动创建所有父目录,已存在时不报错 base_path.mkdir(parents=True, exist_ok=True) # 保存图片 original_image.save(base_path / 'original.jpeg') saliency_image.save(base_path / 'saliency.jpeg')
关键说明
- 两种方法都会自动补全所有缺失的父目录,无需手动逐个创建
- 代码替换了硬编码路径,改为动态生成适配CIFAR10全分类和预测结果的路径
exist_ok=True参数确保循环处理大量图片时,不会因目录已存在抛出异常
内容的提问来源于stack exchange,提问作者m0ss
相关产品推荐
相关产品推荐

