为什么会出现内存错误?蟒蛇

Kan*_*wat 5 python

我有一个5GB的文本文件,我正在尝试逐行阅读。我的文件格式为:: Reviewerid <\ t> pid <\ t> date <\ t> title <\ t> body <\ n>这是我的代码

o = open('mproducts.txt','w')
with open('reviewsNew.txt','rb') as f1:
    for line in f1:
        line = line.strip()
        line2 = line.split('\t')
        o.write(str(line))
        o.write("\n")
Run Code Online (Sandbox Code Playgroud)

但是当我尝试运行它时出现内存错误。我有一个8GB的RAM和1Tb的空间,那为什么我会收到此错误?我试图以块的形式读取它,但随后我也收到了该错误。

MemoryError 
Run Code Online (Sandbox Code Playgroud)

Din*_*kar 4

更新:

安装 64 位 Python 可以解决该问题。

OP 使用 32 位 Python,这就是内存限制的原因。


阅读整个评论我认为这可以帮助你。

  • 由于您想要处理数据,因此无法按块(如 1024)读取文件。
  • 相反,以行块的形式读取文件,即一次读取 N 行。
  • 您可以在Python中使用yield关键字和itertools来实现上述目的。

总结:一次获取N行,处理然后写入。

示例代码:

from itertools import islice
#You can change num_of_lines
def get_lines(file_handle,num_of_lines = 10):
    while True:
        next_n_lines = list(islice(file_handle, num_of_lines))
        if not next_n_lines:
            break
        yield next_n_lines


o = open('mproducts.txt','w')

with open('reviewsNew.txt','r') as f1:
    for data_lines in get_lines(f1):
        for line in data_lines:
            line = line.strip()
            line2 = line.split('\t')
            o.write(str(line))
            o.write("\n")
o.close()
Run Code Online (Sandbox Code Playgroud)