gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:46:03 25 4
gpt4 key购买 nike

相关问题: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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com