首页 > 解决方案 > 读取chucksize后如何写入excel

问题描述

读取chucksize中的文件后如何写入excel文件?

通过pandas将这80k行从文件读入excel后,我不知道如何写谢谢

import os, sys
import pandas as pd
import xlwings as xw

caminho = os.path.abspath(os.path.dirname(sys.argv[0]))
txt = caminho + '\\Fat3.txt'
xls = caminho + '\\cobfat.xlsx'
existe_txt = os.path.exists(txt)
existe_xls = os.path.exists(xls)


def check_path(x):
    # Função para verificar se há arquivo no caminho e com o nome correto. 
    if x != True:
        st = 'O arquivo não foi encontrado.\nVerifique se o nome está no local e com o nome correto.'
    else:
        st = 'ok'
    return st

big_file = 5000

if check_path(existe_txt):
    # Lista para guardados os dados do arquivo
    lst_xl = []

    # Leitura do arquivo usando chuck size
    for df in pd.read_csv(txt, sep="|", header=None, encoding='ISO-8859-1', chunksize=big_file):
        lst_xl.append(df)
        print('Gravando ...', df.shape)

    # Gravar dados no Excel
    df_xl = pd.concat(lst_xl, axis=0)
    writer = pd.ExcelWriter('output.xlsx')
    df_xl.to_excel(writer,'Plan1')
    writer.save()
    # I get error "error memory limit exceeded" after try save this in file.

的堆栈跟踪MemoryError

 File "C:\Users\marreco\AppData\Local\Programs\Python\Python38-32\lib\site-packages\et_xmlfile\xmlfile.py", line 41, in element yield File "C:\Users\marreco\AppData\Local\Programs\Python\Python38-32\lib\site-packages\openpyxl\worksheet_writer.py", line 146, in write_row write_cell(xf, self.ws, cell, cell.has_style) File "C:\Users\marreco\AppData\Local\Programs\Python\Python38-32\lib\site-packages\openpyxl\cell_writer.py", line 45, in etree_write_cell el = Element("c", attributes) MemoryError

标签: python-3.x

解决方案


我不敢相信答案总是如此接近。

xw.Range('A1').value = df_xl

谢谢!


推荐阅读