用python写一个能根据包含图片名称和类别的csv文件将图片分类到对应文件夹的程序
时间: 2024-11-18 21:27:18 浏览: 27
为了实现这个功能,你可以按照以下步骤编写Python代码:
1. **导入必要的库**[^1]:
```python
import os
import csv
import shutil
```
2. **定义要操作的目录结构**:
```python
# 定义根目录和子目录结构
base_dir = "images" # 原始图片文件夹
output_dir = "organized_images" # 分类后的文件夹
sub_dirs = ["train", "test", "validation"] # 类别对应的子目录
for sub_dir in sub_dirs:
os.makedirs(os.path.join(output_dir, sub_dir), exist_ok=True)
```
3. **读取CSV文件**:
```python
def read_csv(file_path):
with open(file_path, newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
next(reader) # 跳过表头
return [(row[0], row[1]) for row in reader]
# 获取csv文件路径(假设在images文件夹内)
train_csv = os.path.join(base_dir, "train.csv")
test_csv = os.path.join(base_dir, "test.csv")
train_data = read_csv(train_csv)
test_data = read_csv(test_csv)
```
4. **遍历CSV数据,移动图片到对应文件夹**:
```python
def move_files(data, subdir):
for img_name, label in data:
source_path = os.path.join(base_dir, img_name)
dest_path = os.path.join(output_dir, subdir, label)
shutil.move(source_path, dest_path)
move_files(train_data, "train")
move_files(test_data, "test")
```
5. **如果还有验证集或其他类别,可以添加相应的读取和移动逻辑**。
完整的示例代码可能看起来像这样:
```python
# ... (前面的导入和定义部分)
# 加载验证集 CSV 文件(如果有)
val_csv = os.path.join(base_dir, "validation.csv")
val_data = read_csv(val_csv)
move_files(val_data, "validation")
# 检查文件移动情况
for subdir in sub_dirs:
print(f"{subdir} directory:")
for root, dirs, files in os.walk(os.path.join(output_dir, subdir)):
print(f"\t{root}")
```
阅读全文