用python写一个能按照一个包含图片名称和类别的csv文件将图片自动分到对应文件夹的程序
时间: 2024-11-18 21:16:40 浏览: 33
要创建一个Python程序来按照CSV文件中的类别信息将图片分到不同的文件夹,你可以遵循以下步骤:
1. 导入所需的库[^1]:
```python
import os
import pandas as pd
from shutil import move # 使用shutil库移动文件更安全
```
2. 读取CSV文件:
```python
# 假设csv文件名为'data.csv',列分别为'image_path'(图片路径)和'label'(类别)
data = pd.read_csv('data.csv')
```
3. 定义文件夹结构:
```python
folder_structure = {
'test': 'path/to/test/folder',
'train': 'path/to/train/folder',
'validation': 'path/to/validation/folder',
'train_valid': 'path/to/train_valid/folder'
}
```
4. 创建或检查文件夹是否存在:
```python
for folder_name in folder_structure.values():
if not os.path.exists(folder_name):
os.makedirs(folder_name)
```
5. 分类并移动图片[^2]:
```python
for index, row in data.iterrows():
image_path = row['image_path']
label = row['label']
destination_folder = folder_structure[label]
full_destination_path = os.path.join(destination_folder, os.path.basename(image_path))
try:
move(image_path, full_destination_path)
print(f"Moved {image_path} to {full_destination_path}")
except Exception as e:
print(f"Error moving file: {e}")
```
这个程序会遍历CSV文件,根据每个条目的类别将图片移动到相应的文件夹内。
阅读全文