python - 将 txt 转换为 xlsx 时出现 MemoryError

标签 python python-2.7 openpyxl

相关问题: 1. Error in converting txt to xlsx using python

  1. Converting txt to xlsx while setting the cell property for number cells as number

我的代码是

    import csv
    import openpyxl

    import sys


    def convert(input_path, output_path):
        """
        Read a csv file (with no quoting), and save its contents in an excel file.
        """
        wb = openpyxl.Workbook()
        ws = wb.worksheets[0]

        with open(input_path) as f:
            reader = csv.reader(f, delimiter='\t', quoting=csv.QUOTE_NONE)
            for row_index, row in enumerate(reader, 1):
                for col_index, value in enumerate(row, 1):
                    ws.cell(row=row_index, column=col_index).value = value
        print 'hello world'

        wb.save(output_path)

        print 'hello world2'


    def main():
        try:
            input_path, output_path = sys.argv[1:]
        except ValueError:
            print 'Usage: python %s input_path output_path' % (sys.argv[0],)
        else:
            convert(input_path, output_path)


    if __name__ == '__main__':
        main()

此代码有效,除了一些输入文件。我找不到导致此问题的输入 txt 和不会导致此问题的输入 txt 之间的区别。

我的第一个猜测是编码。我尝试将输入文件的编码更改为 UTF-8 和带 BOM 的 UTF-8。但这失败了。

我的第二个猜测是它确实使用了太多内存。但是我的电脑有 SSD 和 32 GB 内存。

所以也许这段代码没有充分利用这个 RAM 的容量?

我该如何解决这个问题?

enter image description here 编辑:我添加了那行 打印' Hello World ' 和 打印' Hello World 2' 检查'hello world'之前的所有部分是否正确运行。

我检查了代码打印“hello world”,但不是“hello world2”

所以,看起来真的很有可能 wb.save(输出路径)

是导致问题的原因。

最佳答案

openpyxl 优化了读取和写入大文件的模式。 wb = Workbook(write_only=True) 将启用它。

我还建议您安装 lxml 以提高速度。这些都包含在文档中。

关于python - 将 txt 转换为 xlsx 时出现 MemoryError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32271488/

相关文章:

python - 删除python环境

python - 由于 cffi.api.CDefError 无法使用 pyinstaller

python - 保存数据时保留新行

python - PyQt/PySide 中是否有默认图标?

python-2.7 - 从字符串而不是文件中读取networkx中的点图

postgresql - 如何在 Windows 7 上安装 psycopg2

python - 将列表中的某些值与列中的值匹配

python - 如何将数据写入具有多个工作表的现有 '.xlsx' 文件

python - 使用 openpyxl 模块写入电子表格会创建损坏的电子表格,如何使用 zipfile 模块修复?

Python ValueError : ColumnTransformer, 列顺序不相等