Имеется до 400 000 записей в списке, каждая из которых представляет собой словарь с 30 параметрами.
При сохранении в Excel такого количество записей у заказчика кидает ошибку MemoryError
.
Можно ли как нибудь снизить потребление оперативной памяти?
Лог привести не могу, могу только в виде картинки.
Использую:
pd.DataFrame(items).to_excel(config["output_filename"], index=False)
Возможно я ошибаюсь и это проблема не метода сохранения, а метода превращения в DataFrame.
Log
Traceback (most recent call last):
File "f:/trudvsem.ru/parser_database.py", line 173, in
save_page(products, config["size_save_block"])
File "f:/trudvsem.ru/parser_database.py", line 150, in save_page
append_df_to_excel(config["output_filename"], pd.DataFrame(item))
File "f:/trudvsem.ru/parser_database.py", line 96, in append_df_to_excel
writer.book = load_workbook(filename)
File "C:\Users\Cineofilms\AppData\Local\Programs\Python\Python38-32\lib\site-packages\openpyxl\reader\excel.py", line 314, in load_workbook
reader.read()
File "C:\Users\Cineofilms\AppData\Local\Programs\Python\Python38-32\lib\site-packages\openpyxl\reader\excel.py", line 279, in read
self.read_worksheets()
File "C:\Users\Cineofilms\AppData\Local\Programs\Python\Python38-32\lib\site-packages\openpyxl\reader\excel.py", line 227, in read_worksheets
ws_parser.bind_all()
File "C:\Users\Cineofilms\AppData\Local\Programs\Python\Python38-32\lib\site-packages\openpyxl\worksheet\_reader.py", line 426, in bind_all
self.bind_cells()
File "C:\Users\Cineofilms\AppData\Local\Programs\Python\Python38-32\lib\site-packages\openpyxl\worksheet\_reader.py", line 343, in bind_cells
self.ws._cells[(cell['row'], cell['column'])] = c
MemoryError
Метод
def save_page(items, count):
print("Удаление файла", config["output_filename"])
try:
os.remove(config["output_filename"])
except FileNotFoundError:
print()
len_list = str(len(items))
cnt = 0
for i in range(0, len(items), count):
chunk = pd.DataFrame(items[i:i + count])
if(id == 0):
append_df_to_excel(config["output_filename"], chunk, header=True)
else:
append_df_to_excel(config["output_filename"], chunk, header=False)
cnt += 1
print("Сохранено", str(cnt * count) + "/" + len_list)
Update
Переписал под пагинацию database
def get_database_page_save():
index = 0
while True:
last_index = index + config["size_save_block"] + 1
sql = """SELECT * FROM vacancy WHERE id > %s and id < %s"""
data = (index, last_index)
print("Запрос вакансий с id c", index, "по", last_index)
items = core.database_request(config, sql, data)
print("Данные получены. Количество вакансий", len(items))
if(len(items) == 0):
break
else:
with ThreadPoolExecutor(cpu_count) as executor:
results = executor.map(generation_dict, items)
if(index == 0):
print("Удаление файла", config["output_filename"])
try:
os.remove(config["output_filename"])
except FileNotFoundError:
print()
append_df_to_excel(config["output_filename"], pd.DataFrame(results), header=True)
else:
append_df_to_excel(config["output_filename"], pd.DataFrame(results), header=False)
print("Сохранено", str(last_index - 1), "вакансий")
index = index + config["size_save_block"]
def generation_dict(item):
temp = {
"id": item[0],
"vacancy_id": item[1],
"region": item[2],
"company_ogrn": item[3],
"company_code": item[4],
"company_hr_agency": item[5],
"company_phone": item[6],
"company_inn": item[7],
"company_name": item[8],
"company_email": item[9],
"company_kpp": item[10],
"company_url": item[11],
"creation_date": item[12],
"modify_date": item[13],
"salary": item[14],
"salary_min": item[15],
"salary_max": item[16],
"job_name": item[17],
"vac_url": item[18],
"employment": item[19],
"schedule": item[20],
"duty": item[21],
"specialisation": item[22],
"count_jobs": item[23],
"requirement_education": item[24],
"requirement_qualification": item[25],
"requirement_experience": item[26],
"location": item[27],
"lat": item[28],
"lng": item[29],
"term": item[30],
"currency": item[31]
}
return temp
Core
def database_request(config, sql_request, data=None):
with closing(ps.connect(dbname=config["db_name"], user=config["db_user"], password=config["db_password"], host=config["db_host"])) as conn:
with conn.cursor() as cursor:
if data is None:
cursor.execute(sql_request)
conn.commit()
else:
cursor.execute(sql_request, data)
conn.commit()
try:
return cursor.fetchall()
except:
return None
Сейчас тестирую этот метод. Если добавлять по 10 000, (нужно добавить чуть более 300к), то максимальное потребление ОЗУ составило 4.5GB
Думаю, вообще подход с добавлением по пакетам данных считаю не состоятельным, так как все равно, перед добавлением мы читаем данные из Excel и помещаем в память.
Вот метод, который отвечает за это
def load_workbook(filename, read_only=False, keep_vba=KEEP_VBA,
data_only=False, keep_links=True):
"""Open the given filename and return the workbook
:param filename: the path to open or a file-like object
:type filename: string or a file-like object open in binary mode c.f., :class:`zipfile.ZipFile`
:param read_only: optimised for reading, content cannot be edited
:type read_only: bool
:param keep_vba: preseve vba content (this does NOT mean you can use it)
:type keep_vba: bool
:param data_only: controls whether cells with formulae have either the formula (default) or the value stored the last time Excel read the sheet
:type data_only: bool
:param keep_links: whether links to external workbooks should be preserved. The default is True
:type keep_links: bool
:rtype: :class:`openpyxl.workbook.Workbook`
.. note::
When using lazy load, all worksheets will be :class:`openpyxl.worksheet.iter_worksheet.IterableWorksheet`
and the returned workbook will be read-only.
"""
reader = ExcelReader(filename, read_only, keep_vba,
data_only, keep_links)
reader.read()
return reader.wb