遍历Zip文件统计内部Excel总记录数异常问题求助
问题解决思路
你猜的没错,df = df[:1]就是问题根源——每次处理完一个Excel文件后,你都把结果DataFrame截断成只剩第一行,后面的Zip文件数据根本没法留存,最后自然只输出第一行。
另外原代码逻辑也绕了弯路:你把所有Excel数据都加载到DataFrame里再计数,既浪费内存又容易出错。其实我们根本不需要保留数据,只需要统计每个工作表的行数,累加得到每个Zip的总记录数就行。
修改后的代码
import pandas as pd import zipfile import glob # 统计单个Excel文件的总行数(所有工作表行数相加) def count_excel_rows(xls_path): xl = pd.ExcelFile(xls_path) total_rows = 0 for name in xl.sheet_names: sheet = xl.parse(name, header=None, dtype=str, ignore_index=True) sheet.dropna(axis=1, how='all', inplace=True) # 累加当前工作表的行数 total_rows += len(sheet) return total_rows # 处理所有Zip文件,统计每个Zip的总记录数 def process_files(list_of_files): # 初始化结果DataFrame,存储每个Zip的文件名和总记录数 result_df = pd.DataFrame(columns=['FileName', 'Length']) for file in list_of_files: zip_total = 0 with zipfile.ZipFile(file) as zip_handler: zfiles = zip_handler.namelist() extensions = (".xls", ".xlsx") for zfile in zfiles: if zfile.endswith(extensions): # 统计当前Excel文件的行数,累加到Zip总数中 zip_total += count_excel_rows(zip_handler.open(zfile)) # 将当前Zip的结果添加到结果DataFrame result_df = pd.concat([ result_df, pd.DataFrame({'FileName': [file], 'Length': [zip_total]}) ], ignore_index=True) return result_df input_location = r'O:\Stack\Over\Flow' month_to_process = glob.glob(input_location + "\\2022 - 10\\*.zip") df = process_files(month_to_process) print(df)
关键修改说明
- 把
read_excel_sheets改成count_excel_rows,只返回总行数,不用加载全部数据,大幅节省内存 - 每个Zip单独统计总行数,处理完一个就把结果添加到结果DataFrame,不再覆盖之前的数据
- 彻底移除
df[:1]这种截断数据的操作,保证每个Zip的结果都能留存 - 使用
with语句处理Zip文件,自动关闭文件,避免资源泄漏
运行后就能得到你想要的格式:每一行对应一个Zip文件,显示文件名和该Zip下所有Excel工作表的总记录数。
内容的提问来源于stack exchange,提问作者Jonnyboi
相关产品推荐
相关产品推荐

