我有一个5gb的文本文件,我正在尝试逐行读取它。
我的文件格式为:Reviewerid pid date title body
这是我的代码
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")
但是,当我尝试运行它时出现内存错误。我有一个8GB的RAM和1TB的空间,那我为什么会收到此错误?我试图以块的形式读取它,但随后我也收到了该错误。
MemoryError
最佳答案
更新:
安装64位Python可解决此问题。
OP使用的是32位Python,这就是为什么要限制内存的原因。
阅读整个评论,我认为这可以为您提供帮助。
摘要:一次获取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()
关于python - 为什么会出现内存错误? Python,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40096308/