Skip to main content
 首页 » 编程设计

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

2025年05月04日16wayfarer

相关问题: 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 的容量?

我该如何解决这个问题?

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

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

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

是导致问题的原因。

请您参考如下方法:

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

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