引言
最近有个朋友问我,怎么批量处理几百张产品图片?手动一张张处理太累了。
其实这类批量处理任务用Python几行代码就能搞定,效率能提升好几倍。今天我就分享几个实用的批量处理场景,从图片处理到数据清洗,都是工作中常见的需求。
文章里每个场景我都会提供:
- Trae提示词(教你如何让AI生成代码)
- 完整可运行的代码
- 关键的注意事项
代码我都测试过,直接复制就能用。
一、Trae批量处理能力
1.1 Trae批量处理特性
Trae在批量处理方面有几个明显的优势:
- 多文件操作 - 可以同时处理多个文件,不用一个个来
- 批量代码生成 - 告诉它需求,直接生成代码,省时间
- 并行任务执行 - 利用多核CPU加速,处理速度快
- 错误恢复 - 单个文件失败不影响整体,稳定
- 进度反馈 - 实时显示处理进度,体验好
1.2 批量处理场景
本文涵盖10个常见的批量处理场景:
- 批量文件重命名:按照规则批量重命名文件
- 批量图片处理:调整大小、添加水印、转换格式
- 批量数据清洗:处理CSV、Excel数据
- 批量代码格式化:统一代码风格
- 批量文档生成:从模板生成多个文档
- 批量测试运行:自动化测试多个项目
- 批量部署脚本:部署到多个环境
- 批量日志分析:分析多个日志文件
- 批量API调用:调用API获取数据
- 批量报告生成:生成多个分析报告
二、实战案例:批量图片处理
2.1 场景描述
假设你有一个产品图片文件夹,需要:
- 将所有图片调整为统一大小(800x600)
- 添加水印(如果logo.png存在)
- 转换为JPEG格式
- 按照规则重命名(product_0001.jpg, product_0002.jpg...)
- 生成处理报告
2.2 Trae提示词
用这个提示词让Trae生成代码:
帮我写个Python脚本批量处理图片:
- 读取input_images目录下的所有图片(jpg、png、webp等)
- 统一调整到800x600
- 如果有logo.png就加个水印在右下角
- 转成JPEG格式,质量85%
- 按product_0001.jpg、product_0002.jpg...这样命名
- 保存到output_images目录
- 生成个处理报告,统计成功失败数量和耗时
用Pillow库,代码要能直接跑,加个try-except错误处理,显示处理进度。
2.3 依赖说明
运行本代码需要安装以下依赖库:
# 安装Pillow库(图片处理)
pip install Pillow
依赖库说明:
- Pillow:Python图像处理库,用于图片的读取、调整大小、添加水印、格式转换等操作
2.4 完整代码
# batch_process.py
import os
from PIL import Image, ImageDraw, ImageFont
import time
from datetime import datetime
def create_test_images():
"""创建测试图片"""
colors = [
(255, 0, 0), (0, 255, 0), (0, 0, 255),
(255, 255, 0), (255, 0, 255), (0, 255, 255)
]
if not os.path.exists('input_images'):
os.makedirs('input_images')
for i in range(10):
img = Image.new('RGB', (1200, 900), colors[i % len(colors)])
draw = ImageDraw.Draw(img)
try:
font = ImageFont.truetype("arial.ttf", 40)
except:
font = ImageFont.load_default()
text = f"Product {i+1}"
draw.text((400, 400), text, fill=(255, 255, 255), font=font)
if i < 4:
img.save(f'input_images/product{i+1}.jpg')
elif i < 7:
img.save(f'input_images/product{i+1}.png')
else:
img.save(f'input_images/product{i+1}.webp')
print("测试图片已创建在 input_images/ 目录")
def create_watermark():
"""创建测试水印图片"""
watermark = Image.new('RGBA', (200, 50), (255, 255, 255, 128))
draw = ImageDraw.Draw(watermark)
try:
font = ImageFont.truetype("arial.ttf", 30)
except:
font = ImageFont.load_default()
draw.text((10, 10), "Watermark", fill=(0, 0, 0, 200), font=font)
watermark.save('logo.png')
print("水印图片已创建: logo.png")
def add_watermark(image, watermark_path='logo.png'):
"""
添加水印到图片
参数:
image: PIL Image对象
watermark_path: 水印图片路径
返回:
添加水印后的图片
"""
if not os.path.exists(watermark_path):
return image
watermark = Image.open(watermark_path)
watermark = watermark.convert("RGBA")
# 计算水印位置(右下角)
position = (image.size[0] - watermark.size[0] - 10,
image.size[1] - watermark.size[1] - 10)
# 创建透明图层
transparent = Image.new('RGBA', image.size, (0, 0, 0, 0))
transparent.paste(watermark, position, watermark)
# 合并图片
image = image.convert('RGBA')
image = Image.alpha_composite(image, transparent)
image = image.convert('RGB')
return image
def process_image(input_path, output_path, watermark_path='logo.png'):
"""
处理单张图片
参数:
input_path: 输入图片路径
output_path: 输出图片路径
watermark_path: 水印图片路径
返回:
(成功状态, 错误信息)
"""
try:
# 打开图片
img = Image.open(input_path)
# 转换为RGB模式(处理RGBA图片)
if img.mode in ('RGBA', 'LA', 'P'):
img = img.convert('RGB')
# 调整大小(使用LANCZOS重采样)
img = img.resize((800, 600), Image.LANCZOS)
# 添加水印
img = add_watermark(img, watermark_path)
# 保存为JPEG格式,质量85%
img.save(output_path, 'JPEG', quality=85, optimize=True)
return (True, None)
except Exception as e:
return (False, str(e))
def batch_process_images(input_dir='input_images',
output_dir='output_images',
watermark_path='logo.png'):
"""
批量处理图片
参数:
input_dir: 输入目录
output_dir: 输出目录
watermark_path: 水印图片路径
返回:
处理报告字典
"""
start_time = time.time()
# 创建输出目录
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# 获取所有图片文件
image_extensions = ['.jpg', '.jpeg', '.png', '.webp', '.bmp', '.gif']
image_files = []
for file in os.listdir(input_dir):
if os.path.splitext(file)[1].lower() in image_extensions:
image_files.append(file)
# 按文件名排序
image_files.sort()
# 初始化统计信息
report = {
'total': len(image_files),
'success': 0,
'failed': 0,
'failed_files': [],
'start_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'end_time': None,
'duration': None
}
print(f"\n开始处理 {report['total']} 张图片...")
print("=" * 50)
# 批量处理图片
for i, filename in enumerate(image_files, 1):
input_path = os.path.join(input_dir, filename)
output_filename = f"product_{i:04d}.jpg"
output_path = os.path.join(output_dir, output_filename)
# 处理图片
success, error = process_image(input_path, output_path, watermark_path)
if success:
report['success'] += 1
print(f"[{i}/{report['total']}] ✓ {filename} -> {output_filename}")
else:
report['failed'] += 1
report['failed_files'].append({
'file': filename,
'error': error
})
print(f"[{i}/{report['total']}] ✗ {filename} - 错误: {error}")
# 每处理10张图片打印进度
if i % 10 == 0:
print(f"\n进度: {i}/{report['total']} ({i/report['total']*100:.1f}%)")
# 计算处理时间
end_time = time.time()
duration = end_time - start_time
report['end_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
report['duration'] = f"{duration:.2f}秒"
print("=" * 50)
print(f"\n处理完成!")
print(f"成功: {report['success']} 张")
print(f"失败: {report['failed']} 张")
print(f"耗时: {report['duration']}")
return report
def save_report(report, report_path='report.txt'):
"""
保存处理报告
参数:
report: 处理报告字典
report_path: 报告保存路径
"""
with open(report_path, 'w', encoding='utf-8') as f:
f.write("图片批量处理报告\n")
f.write("=" * 50 + "\n\n")
f.write(f"开始时间: {report['start_time']}\n")
f.write(f"结束时间: {report['end_time']}\n")
f.write(f"处理耗时: {report['duration']}\n\n")
f.write(f"总图片数: {report['total']}\n")
f.write(f"成功处理: {report['success']}\n")
f.write(f"失败处理: {report['failed']}\n\n")
if report['failed_files']:
f.write("失败文件列表:\n")
f.write("-" * 50 + "\n")
for failed in report['failed_files']:
f.write(f"文件: {failed['file']}\n")
f.write(f"错误: {failed['error']}\n\n")
print(f"\n处理报告已保存: {report_path}")
def main():
"""
主函数
"""
print("图片批量处理工具")
print("=" * 50)
# 创建测试数据
print("\n步骤1: 创建测试数据...")
create_test_images()
create_watermark()
# 批量处理图片
print("\n步骤2: 批量处理图片...")
report = batch_process_images(
input_dir='input_images',
output_dir='output_images',
watermark_path='logo.png'
)
# 保存报告
print("\n步骤3: 生成处理报告...")
save_report(report)
print("\n所有任务完成!")
print(f"处理后的图片保存在: output_images/")
print(f"处理报告保存在: report.txt")
if __name__ == "__main__":
main()
2.5 运行步骤
# 步骤1:安装依赖
pip install Pillow
# 步骤2:运行批量处理程序
python batch_process.py
2.6 运行结果
运行成功后,你将看到:
图片批量处理工具
==================================================
步骤1: 创建测试数据...
测试图片已创建在 input_images/ 目录
水印图片已创建: logo.png
步骤2: 批量处理图片...
开始处理 10 张图片...
==================================================
[1/10] ✓ product1.jpg -> product_0001.jpg
[2/10] ✓ product2.jpg -> product_0002.jpg
[3/10] ✓ product3.jpg -> product_0003.jpg
[4/10] ✓ product4.jpg -> product_0004.jpg
[5/10] ✓ product5.png -> product_0005.jpg
[6/10] ✓ product6.png -> product_0006.jpg
[7/10] ✓ product7.png -> product_0007.jpg
[8/10] ✓ product8.webp -> product_0008.jpg
[9/10] ✓ product9.webp -> product_0009.jpg
[10/10] ✓ product10.webp -> product_0010.jpg
==================================================
处理完成!
成功: 10 张
失败: 0 张
耗时: 2.34秒
步骤3: 生成处理报告...
处理报告已保存: report.txt
所有任务完成!
处理后的图片保存在: output_images/
处理报告保存在: report.txt
2.7 生成的文件
input_images/:输入图片目录(包含10张测试图片)output_images/:输出图片目录(包含处理后的图片)logo.png:水印图片report.txt:处理报告
三、其他批量处理场景
3.1 场景1:批量文件重命名
3.1.1 Trae提示词
写个Python脚本批量重命名文件:
- 读取指定目录下的所有文件
- 用正则表达式匹配文件名
- 按规则批量重命名
- 跳过目录,只处理文件
- 显示重命名进度和结果
用os和re模块,代码要能直接跑,加个错误处理。
3.1.2 依赖说明
本代码使用Python标准库,无需安装额外依赖。
依赖库说明:
- os:Python标准库,用于文件和目录操作
- re:Python标准库,用于正则表达式匹配
3.1.3 完整代码
# batch_rename.py
import os
import re
def batch_rename_files(directory, pattern, replacement):
"""
批量重命名文件
参数:
directory: 目录路径
pattern: 正则表达式模式
replacement: 替换字符串
"""
files = os.listdir(directory)
renamed_count = 0
for filename in files:
# 跳过目录
if os.path.isdir(os.path.join(directory, filename)):
continue
# 应用正则表达式
new_filename = re.sub(pattern, replacement, filename)
# 如果文件名有变化,则重命名
if new_filename != filename:
old_path = os.path.join(directory, filename)
new_path = os.path.join(directory, new_filename)
os.rename(old_path, new_path)
print(f"重命名: {filename} -> {new_filename}")
renamed_count += 1
print(f"\n共重命名 {renamed_count} 个文件")
def main():
"""
主函数
"""
# 示例:将文件名中的空格替换为下划线
batch_rename_files('.', r'\s+', '_')
# 示例:将文件名中的小写字母转换为大写
# batch_rename_files('.', r'[a-z]', lambda m: m.group().upper())
if __name__ == "__main__":
main()
3.2 场景3:批量数据清洗
3.2.1 Trae提示词
写个Python脚本批量清洗数据:
- 读取input_data目录下的所有CSV文件
- 对每个CSV文件进行数据清洗:
- 删除包含空值的行
- 删除重复行
- 删除异常值(用3σ规则)
- 将清洗后的数据保存到output_data目录
- 生成清洗报告,包括成功/失败数量
用pandas库,代码要能直接跑,加个try-except错误处理,显示清洗进度。
3.2.2 依赖说明
运行本代码需要安装以下依赖库:
# 安装pandas库(数据处理)
pip install pandas
依赖库说明:
- pandas:Python数据分析库,用于数据读取、清洗、处理等操作
3.2.3 完整代码
# batch_clean_data.py
import pandas as pd
import os
def clean_csv_file(input_path, output_path):
"""
清洗CSV文件
参数:
input_path: 输入文件路径
output_path: 输出文件路径
"""
try:
# 读取CSV文件
df = pd.read_csv(input_path)
# 数据清洗步骤
# 1. 删除空值
df = df.dropna()
# 2. 删除重复行
df = df.drop_duplicates()
# 3. 删除异常值(假设数值列)
numeric_columns = df.select_dtypes(include=['int64', 'float64']).columns
for col in numeric_columns:
mean = df[col].mean()
std = df[col].std()
df = df[(df[col] >= mean - 3*std) & (df[col] <= mean + 3*std)]
# 保存清洗后的数据
df.to_csv(output_path, index=False)
return True
except Exception as e:
print(f"处理 {input_path} 时出错: {str(e)}")
return False
def batch_clean_data(input_dir, output_dir):
"""
批量清洗数据文件
参数:
input_dir: 输入目录
output_dir: 输出目录
"""
if not os.path.exists(output_dir):
os.makedirs(output_dir)
csv_files = [f for f in os.listdir(input_dir) if f.endswith('.csv')]
success_count = 0
for csv_file in csv_files:
input_path = os.path.join(input_dir, csv_file)
output_path = os.path.join(output_dir, f"cleaned_{csv_file}")
if clean_csv_file(input_path, output_path):
success_count += 1
print(f"✓ {csv_file} -> cleaned_{csv_file}")
else:
print(f"✗ {csv_file}")
print(f"\n成功清洗 {success_count}/{len(csv_files)} 个文件")
def create_test_data():
"""
创建测试数据
"""
import numpy as np
if not os.path.exists('input_data'):
os.makedirs('input_data')
for i in range(3):
# 创建测试数据
data = {
'id': range(1, 101),
'value': np.random.normal(100, 20, 100),
'category': np.random.choice(['A', 'B', 'C'], 100)
}
# 添加一些空值和异常值
df = pd.DataFrame(data)
df.loc[10:15, 'value'] = np.nan
df.loc[20, 'value'] = 1000 # 异常值
# 保存CSV
df.to_csv(f'input_data/data_{i+1}.csv', index=False)
print("测试数据已创建在 input_data/ 目录")
def main():
"""
主函数
"""
print("批量数据清洗工具")
print("=" * 50)
# 创建测试数据
print("\n创建测试数据...")
create_test_data()
# 批量清洗数据
print("\n批量清洗数据...")
batch_clean_data('input_data', 'output_data')
print("\n所有任务完成!")
if __name__ == "__main__":
main()
3.3 场景5:批量文档生成
3.3.1 Trae提示词
写个Python脚本批量生成文档:
- 读取报告模板文件(template.txt)
- 根据数据列表批量生成多个报告
- 将生成的报告保存到reports目录
- 显示生成进度
用Python标准库,代码要能直接跑,加个错误处理。
3.3.2 依赖说明
本代码使用Python标准库,无需安装额外依赖。
依赖库说明:
- os:Python标准库,用于文件和目录操作
- datetime:Python标准库,用于日期时间处理
3.3.3 完整代码
# batch_generate_docs.py
import os
from datetime import datetime
def generate_report(template, data, output_path):
"""
生成报告文档
参数:
template: 模板字符串
data: 数据字典
output_path: 输出文件路径
"""
# 替换模板变量
content = template.format(**data)
# 保存文档
with open(output_path, 'w', encoding='utf-8') as f:
f.write(content)
def batch_generate_reports(template_path, data_list, output_dir):
"""
批量生成报告
参数:
template_path: 模板文件路径
data_list: 数据列表
output_dir: 输出目录
"""
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# 读取模板
with open(template_path, 'r', encoding='utf-8') as f:
template = f.read()
# 批量生成报告
for i, data in enumerate(data_list, 1):
output_path = os.path.join(output_dir, f"report_{i}.txt")
generate_report(template, data, output_path)
print(f"✓ 生成报告: report_{i}.txt")
def create_template():
"""
创建报告模板
"""
template = """# {title}
**日期**: {date}
**作者**: {author}
**部门**: {department}
## 摘要
{summary}
## 详细内容
{content}
## 结论
{conclusion}
---
*报告生成时间: {timestamp}*
"""
with open('template.txt', 'w', encoding='utf-8') as f:
f.write(template)
print("报告模板已创建: template.txt")
def create_test_data():
"""
创建测试数据
"""
data_list = [
{
'title': '项目进度报告 - 第一季度',
'date': '2025-01-15',
'author': '张三',
'department': '技术部',
'summary': '第一季度项目进展顺利,完成了主要功能开发。',
'content': '在本季度中,我们完成了以下工作:\n1. 完成了用户管理模块\n2. 完成了订单处理模块\n3. 进行了系统测试',
'conclusion': '项目按计划进行,预计下季度可以完成所有功能。',
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
},
{
'title': '项目进度报告 - 第二季度',
'date': '2025-04-15',
'author': '李四',
'department': '产品部',
'summary': '第二季度项目进展顺利,完成了所有功能开发。',
'content': '在本季度中,我们完成了以下工作:\n1. 完成了数据分析模块\n2. 完成了报表生成模块\n3. 进行了性能优化',
'conclusion': '项目提前完成,可以进入测试阶段。',
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
]
return data_list
def main():
"""
主函数
"""
print("批量文档生成工具")
print("=" * 50)
# 创建模板
print("\n创建报告模板...")
create_template()
# 创建测试数据
print("\n创建测试数据...")
data_list = create_test_data()
# 批量生成报告
print("\n批量生成报告...")
batch_generate_reports('template.txt', data_list, 'reports')
print("\n所有任务完成!")
print(f"报告保存在: reports/")
if __name__ == "__main__":
main()
四、批量处理最佳实践
4.1 错误处理
def safe_process(file_path, process_func):
"""
安全处理文件
参数:
file_path: 文件路径
process_func: 处理函数
返回:
(成功状态, 结果或错误信息)
"""
try:
result = process_func(file_path)
return (True, result)
except FileNotFoundError:
return (False, f"文件不存在: {file_path}")
except PermissionError:
return (False, f"没有权限访问: {file_path}")
except Exception as e:
return (False, f"处理错误: {str(e)}")
4.2 进度显示
def show_progress(current, total, prefix="进度"):
"""
显示进度
参数:
current: 当前进度
total: 总数
prefix: 前缀文本
"""
percent = (current / total) * 100
bar_length = 50
filled = int(bar_length * current / total)
bar = '█' * filled + '-' * (bar_length - filled)
print(f'\r{prefix}: |{bar}| {percent:.1f}% ({current}/{total})', end='')
if current == total:
print()
4.3 日志记录
import logging
def setup_logger(log_file='batch_process.log'):
"""
配置日志记录器
参数:
log_file: 日志文件路径
返回:
logger对象
"""
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(log_file, encoding='utf-8'),
logging.StreamHandler()
]
)
return logging.getLogger(__name__)
# 使用示例
logger = setup_logger()
logger.info("开始批量处理")
logger.error("处理失败: 文件损坏")
五、常见问题与解决方案
5.1 问题:内存不足
问题描述:处理大量文件时内存不足。
解决方案:
def process_large_files(file_list, batch_size=100):
"""
分批处理大文件
参数:
file_list: 文件列表
batch_size: 每批处理的文件数量
"""
for i in range(0, len(file_list), batch_size):
batch = file_list[i:i+batch_size]
process_batch(batch)
# 手动触发垃圾回收
import gc
gc.collect()
5.2 问题:处理速度慢
问题描述:批量处理速度太慢。
解决方案:
from concurrent.futures import ThreadPoolExecutor
import multiprocessing
def parallel_process(file_list, max_workers=None):
"""
并行处理文件
参数:
file_list: 文件列表
max_workers: 最大工作线程数
"""
if max_workers is None:
max_workers = multiprocessing.cpu_count()
with ThreadPoolExecutor(max_workers=max_workers) as executor:
results = list(executor.map(process_file, file_list))
return results
5.3 问题:文件路径问题
问题描述:在Windows和Linux上路径不兼容。
解决方案:
import os
def get_path(*parts):
"""
获取跨平台兼容的路径
参数:
*parts: 路径部分
返回:
完整路径
"""
return os.path.join(*parts)
# 使用示例
input_path = get_path('data', 'input', 'file.csv')
六、总结
好了,这次的分享就到这里。通过这些例子,你应该能学会:
- Trae批量处理能力 - 了解Trae在批量处理方面的优势
- 完整的实战案例 - 批量图片处理的完整代码
- 其他批量处理场景 - 文件重命名、数据清洗、文档生成等
- 最佳实践 - 错误处理、进度显示、日志记录
- 可运行的代码 - 所有代码都可以直接运行
关键要点
✅ 错误处理 - 用try-except捕获异常,记录失败信息
✅ 进度反馈 - 实时显示处理进度,提升用户体验
✅ 日志记录 - 记录处理过程,方便问题排查
✅ 跨平台兼容 - 用os.path处理路径,兼容不同操作系统
✅ 性能优化 - 用多线程/多进程加速处理
下一步
掌握了这些基础技巧后,你可以继续学习其它内容!🚀
👉 最新发布点击关注 @效率客栈老秦 解锁更多深度干货!
💡 如果你觉得有收获,欢迎点个【赞】或【收藏】💡
