使用readline进行python采样会导致内存错误

时间:2018-10-31 23:23:15

标签: python memory readline sampling

我试图对一个超过2.6亿行的数据文件进行采样,创建了一个均匀分布的样本,固定大小为1000个样本。

我所做的是:

import random

file = "input.txt"
output = open("output.txt", "w+", encoding = "utf-8")

samples = random.sample(range(1, 264000000), 1000)
samples.sort(reverse=False)

with open(file, encoding = "utf-8") as fp:
    line = fp.readline()
    count = 0
    while line:
        if count in samples:
            output.write(line)
            samples.remove(count)
        count += 1
        line = fp.readline()

此代码导致内存错误,没有进一步的描述。这段代码怎么会导致内存错误?

据我所知,它应该逐行读取我的文件。该文件为28.4GB,因此无法整体读取,这就是为什么我诉诸readline()方法的原因。我该如何解决这个问题,以便无论文件大小如何都可以处理整个文件?\

编辑: 最新的尝试会抛出此错误,实际上与我到目前为止获得的每个先前的错误消息相同

MemoryError                               Traceback (most recent call last)
<ipython-input-1-a772dad1ea5a> in <module>()
     12 with open(file, encoding = "utf-8") as fp:
     13     count = 0
---> 14     for line in fp:
     15         if count in samples:
     16             output.write(line)

~\Anaconda3\lib\codecs.py in decode(self, input, final)
    320         # decode input (taking the buffer into account)
    321         data = self.buffer + input
--> 322         (result, consumed) = self._buffer_decode(data, self.errors, final)
    323         # keep undecoded input until the next call
    324         self.buffer = data[consumed:]

MemoryError: 

2 个答案:

答案 0 :(得分:0)

所以看起来这行会导致巨大的内存峰值:

callback()

我的猜测是,此调用会强制python在进行采样之前创建该范围内的所有264M int。尝试使用以下代码在相同范围内进行采样而不进行替换:

getUserMedia

答案 1 :(得分:0)

已解决

我终于解决了这个问题:这里的所有代码都能正常工作, 范围问题确实仅在3.0之前的版本中存在, 应该是xrange(1,264000000)。

输入文件是用其他代码文件构造的, 编写如下:

with open(file, encoding = "utf-8", errors = 'ignore') as fp:  
line = fp.readline()
    while line:
        input_line = line.split(sep="\t")
        output.write(input_line[1] + "," + input_line[2])
        line = fp.readline()

这里的问题是此代码不会用行构造文件,而只是将信息添加到第一行。因此,整个文件被读为一行大行,而不是一个有很多行要重复的文件。

非常感谢您的帮助和由衷的歉意,因为问题出在我项目的其他地方。