前段时间用python3读取大excel文件,读取过程中,内存耗尽,程序也报错了,本文记录一下python3读取大文件时内存耗尽的解决方法。
一、导入代码
原始代码,执行后内存耗尽
from openpyxl import load_workbook
def read_excel():
# 打开excel文件
wb = load_workbook(filename='客户资料.xlsx')
# 获取并打印 sheet 数量
# print("sheet 数量:", wb.sheetnames, type(wb.sheetnames))
sheet_ranges = wb[wb.sheetnames[0]]
# 计算处理进度
count, total = 0, 0
# 获取行列数
row, column = sheet_ranges.max_row, sheet_ranges.max_column
total = row
print(count, total, column)
for sheet in sheet_ranges:
count += 1
print('进度:{0}%'.format(round(count * 100 / total, 2)), sheet[2].value)
执行结果
改进后的代码,正常读取
from openpyxl import load_workbook
import io
def read_excel():
# 打开excel文件
xlsx_filename = '客户资料.xlsx'
with open(xlsx_filename, "rb") as f: # 解决读取打文件时,内存没释放导致内存耗尽的情况
in_mem_file = io.BytesIO(f.read())
wb = load_workbook(in_mem_file, read_only=True)
# 获取并打印 sheet 数量
# print("sheet 数量:", wb.sheetnames, type(wb.sheetnames))
sheet_ranges = wb[wb.sheetnames[0]]
# 计算处理进度
count, total = 0, 0
# 获取行列数
row, column = sheet_ranges.max_row, sheet_ranges.max_column
total = row
print(count, total, column)
for sheet in sheet_ranges:
count += 1
print('进度:{0}%'.format(round(count * 100 / total, 2)), sheet[2].value)
执行结果
从上面截图可以看出处理过程中,内存占用不高,数据也读取完成。
二、总结
io.BytesIO能处理excel文件,还能处理文本文件、二进制文件等