Python批量处理Excel与CSV文件实战指南

📅 2026/8/4 14:51:56
Python批量处理Excel与CSV文件实战指南
1. 为什么需要批量处理Excel和CSV文件在日常办公和数据处理中我们经常遇到需要同时处理多个Excel或CSV文件的情况。比如财务人员每月要汇总几十个部门的报表市场人员需要整理来自不同渠道的销售数据科研工作者要处理实验仪器导出的多组数据文件。手动一个个打开文件操作不仅效率低下还容易出错。Python作为数据处理领域的利器提供了丰富的库来高效完成这些重复性工作。通过编写简单的脚本我们可以实现自动合并多个文件的数据批量修改文件格式或内容快速提取关键信息定时执行数据处理任务2. 环境准备与基础工具2.1 Python环境配置建议使用Python 3.6版本安装时勾选Add Python to PATH选项。验证安装成功python --version pip --version2.2 核心库安装处理Excel和CSV文件主要依赖以下库pip install pandas openpyxl xlrdpandas数据处理核心库openpyxl处理xlsx格式Excel文件xlrd兼容旧版xls格式3. 文件读取与基础操作3.1 读取单个Excel文件import pandas as pd # 读取整个文件 df pd.read_excel(data.xlsx, sheet_nameSheet1) # 只读取特定列 df pd.read_excel(data.xlsx, usecols[姓名,销售额]) # 处理大文件时建议指定dtype df pd.read_excel(data.xlsx, dtype{ID:str})3.2 读取CSV文件# 基本读取 df pd.read_csv(data.csv) # 处理编码问题 df pd.read_csv(data.csv, encodinggbk) # 中文常用编码 # 跳过指定行 df pd.read_csv(data.csv, skiprows[1,3])4. 批量处理实战技巧4.1 多文件合并import os all_data [] folder_path ./data_files for file in os.listdir(folder_path): if file.endswith(.xlsx): file_path os.path.join(folder_path, file) df pd.read_excel(file_path) all_data.append(df) combined pd.concat(all_data) combined.to_excel(merged.xlsx, indexFalse)4.2 批量修改内容def process_file(file_path): df pd.read_excel(file_path) # 统一日期格式 df[日期] pd.to_datetime(df[日期]).dt.strftime(%Y-%m-%d) # 金额单位转换 df[金额] df[金额] * 100 return df5. 性能优化与问题排查5.1 处理大文件技巧# 分块读取 chunk_size 10000 chunks pd.read_csv(large.csv, chunksizechunk_size) for chunk in chunks: process(chunk) # 指定数据类型减少内存占用 dtypes {ID:int32, Price:float32} df pd.read_csv(data.csv, dtypedtypes)5.2 常见问题解决问题1读取速度慢解决方案使用engineopenpyxl参数或转换为CSV处理问题2编码错误尝试常见编码utf-8、gbk、gb2312、latin1问题3日期格式混乱df[日期] pd.to_datetime(df[日期], errorscoerce)6. 高级应用场景6.1 自动化报表生成from datetime import datetime report_date datetime.now().strftime(%Y%m%d) writer pd.ExcelWriter(freport_{report_date}.xlsx, enginexlsxwriter) # 添加多个sheet df_summary.to_excel(writer, sheet_name汇总) df_details.to_excel(writer, sheet_name明细) # 设置格式 workbook writer.book format workbook.add_format({num_format: #,##0}) writer.sheets[汇总].set_column(B:B, None, format) writer.save()6.2 与数据库交互from sqlalchemy import create_engine # 导出到数据库 engine create_engine(mysqlpymysql://user:passlocalhost/db) df.to_sql(table_name, engine, if_existsappend, indexFalse) # 从数据库读取 query SELECT * FROM sales WHERE date 2023-01-01 df pd.read_sql(query, engine)7. 实用技巧与注意事项文件备份处理前先复制原始文件import shutil shutil.copy2(data.xlsx, backup/data_backup.xlsx)异常处理try: df pd.read_excel(data.xlsx) except Exception as e: print(f读取文件出错: {str(e)})进度显示from tqdm import tqdm files [f for f in os.listdir() if f.endswith(.csv)] for file in tqdm(files, desc处理进度): process_file(file)内存管理及时删除不再使用的DataFramedel df使用df.info(memory_usagedeep)查看内存占用多进程加速from multiprocessing import Pool def process_file(file): # 处理逻辑 return result with Pool(4) as p: # 4个进程 results p.map(process_file, file_list)8. 完整案例销售数据月报自动化假设我们需要每月处理各区域销售数据生成汇总报表import pandas as pd import os from datetime import datetime def generate_monthly_report(month): # 1. 读取各区域数据 region_files [f for f in os.listdir(regional_sales) if f.startswith(fsales_{month})] all_data [] for file in region_files: df pd.read_excel(fregional_sales/{file}) df[区域] file.split(_)[2].split(.)[0] all_data.append(df) # 2. 合并数据 combined pd.concat(all_data) # 3. 数据清洗 combined[销售额] combined[销售额].str.replace(,,).astype(float) combined combined.dropna(subset[客户ID]) # 4. 计算指标 report combined.groupby(区域).agg({ 销售额: [sum,mean,count], 利润: sum }) # 5. 输出报表 report_date datetime.now().strftime(%Y%m%d) with pd.ExcelWriter(freports/sales_report_{report_date}.xlsx) as writer: report.to_excel(writer, sheet_name汇总) combined.to_excel(writer, sheet_name明细数据) print(f报表已生成: sales_report_{report_date}.xlsx) # 执行 generate_monthly_report(202303)这个案例展示了从数据收集、清洗、分析到报表输出的完整流程实际应用中可以根据需求调整每个步骤的具体实现。