convert large csv file to excel using python 3

為{幸葍}努か 提交于 2019-12-11 07:29:53

问题


this is my code covert csv file to xlsx file, for small size CSV file this code is working fine, but when I tried for larger size CSV files, Its shows an error.

import os
import glob
import csv
from xlsxwriter.workbook import Workbook

for csvfile in glob.glob(os.path.join('.', 'file.csv')):
    workbook = Workbook(csvfile[:-4] + '.xlsx')
    worksheet = workbook.add_worksheet()
    with open(csvfile, 'r', encoding='utf8') as f:
        reader = csv.reader(f)
        for r, row in enumerate(reader):
            for c, col in enumerate(row):
                worksheet.write(r, c, col)
    workbook.close()

the error is

File "CsvToExcel.py", line 12, in <module>
for r, row in enumerate(reader):
_csv.Error: field larger than field limit (131072)
Exception ignored in: <bound method Workbook.__del__ of 
<xlsxwriter.workbook.Workbook object at 0x7fff4e731470>>
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/xlsxwriter/workbook.py", line 
153, in __del__
Exception: Exception caught in workbook destructor. Explicit close() may be 
required for workbook.

回答1:


While using large files, it's better to use 'constant_memory' for controlled memory usage like:

workbook = Workbook(csvfile + '.xlsx', {'constant_memory': True}).

Ref: xlsxwriter.readthedocs.org/en/latest/working_with_memory.htm‌​l



来源:https://stackoverflow.com/questions/47330674/convert-large-csv-file-to-excel-using-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!