
本文介绍使用 Python 自动遍历指定目录下所有 .xlsx 文件,逐个读取并保存为同名 .csv 文件的完整方案,避免硬编码路径和文件名,提升代码可移植性与健壮性。
本文介绍使用 python 自动遍历指定目录下所有 `.xlsx` 文件,逐个读取并保存为同名 `.csv` 文件的完整方案,避免硬编码路径和文件名,提升代码可移植性与健壮性。
要实现 Excel 批量转 CSV 的自动化处理,核心在于:动态发现文件、安全构造路径、统一处理逻辑。以下是一个生产就绪的教程式实现:
诊断并修复涉及公式、命名范围、Power Query 刷新、数据透视表、VBA/宏保存等问题的 Microsoft Excel XLSX 工作簿
✅ 基础实现(推荐初学者使用)
import os
import pandas as pd
# 配置输入输出路径(可自由修改,无需硬编码具体文件名)
source_directory = "/input_files/"
output_directory = os.path.join(source_directory, "input_csv_files")
# 确保输出目录存在,避免 FileNotFoundError
os.makedirs(output_directory, exist_ok=True)
# 获取所有 .xlsx 文件(忽略隐藏文件及非 Excel 文件)
all_excel_files = [
f for f in os.listdir(source_directory)
if f.endswith(".xlsx") and os.path.isfile(os.path.join(source_directory, f))
]
# 逐个处理
for filename in all_excel_files:
# 构建完整输入路径
input_path = os.path.join(source_directory, filename)
# 读取 Excel(自动识别 sheet,默认读取第一个 sheet)
try:
df = pd.read_excel(input_path)
except Exception as e:
print(f"⚠️ 跳过文件 {filename}:读取失败 — {e}")
continue
# 构建输出 CSV 路径(替换扩展名为 .csv)
csv_filename = os.path.splitext(filename)[0] + ".csv"
output_path = os.path.join(output_directory, csv_filename)
# 保存为 CSV,不写入索引,保留表头
df.to_csv(output_path, index=False, header=True)
print(f"✅ 已保存:{filename} → {csv_filename}")? 关键说明与最佳实践
- 路径安全:使用 os.path.join() 替代字符串拼接,兼容 Windows/macOS/Linux;
- 容错处理:添加 try-except 捕获读取异常(如损坏文件、密码保护表),避免单个失败中断整个流程;
- 目录保障:os.makedirs(..., exist_ok=True) 确保输出文件夹自动创建,无需手动准备;
- 文件过滤强化:os.path.isfile() 排除子目录,防止 os.listdir() 返回文件夹名导致错误;
- 扩展名处理:os.path.splitext(filename)[0] 精准提取主文件名,比字符串切片更可靠(如支持 report_v2.1.xlsx)。
? 进阶建议(按需启用)
- 若需处理多个 sheet,可传入 sheet_name=None 得到 dict,再分别保存为 name_sheet1.csv;
- 加入日志模块(logging)替代 print,便于集成到服务中;
- 使用 glob 模块替代 os.listdir:
from glob import glob excel_files = glob(os.path.join(source_directory, "*.xlsx"))
- 对于超大 Excel 文件,考虑分块读取(chunksize= 参数)或改用 openpyxl/calamine 提升性能。
该方案简洁、健壮、可维护,适用于数据管道、ETL 脚本或 Web 后端文件预处理场景。只需修改 source_directory 即可复用于任意环境,真正实现“一次编写,随处运行”。

















