64 位系统,8gb 内存,多于 800MB 的 CSV,用 python 读取会出现内存错误

64 bit system, 8gb of ram, a bit more than 800MB of CSV and reading with python gives memory error

f = open("data.csv")
f.seek(0) 
f_reader = csv.reader(f)
raw_data = np.array(list(islice(f_reader,0,10000000)),dtype = int)

以上是我用来读取 csv 文件的代码。 csv 文件只有大约 800 MB,我使用的是 64 位 系统和 8GB 的 Ram。该文件包含 1 亿行。然而,更不用说读取整个文件,即使读取前 1000 万行也会出现“MemoryError:”<- 这实际上是整个错误消息。

有人能告诉我为什么吗?另外作为附带问题,有人可以告诉我如何读取,请说第 2000 万行吗?我知道我需要使用 f.seek(some number) 但由于我的数据是一个 csv 文件,我不知道应该将哪个数字准确地放入 f.seek() 以便它从第 20 行准确读取。

非常感谢。

could someone tell me how to read from, say the 20th million row please? I know I need to use f.seek(some number)

不,您不能(也不能)在这种情况下使用 f.seek()。相反,您必须以某种方式读取前 2000 万行中的每一行。

Python documentation 有这个收件人:

def consume(iterator, n):
    "Advance the iterator n-steps ahead. If n is none, consume entirely."
    # Use functions that consume iterators at C speed.
    if n is None:
        # feed the entire iterator into a zero-length deque
        collections.deque(iterator, maxlen=0)
    else:
        # advance to the empty slice starting at position n
        next(islice(iterator, n, n), None)

使用它,您将在 20,000,000 行之后开始:

#UNTESTED
f = open("data.csv")
f_reader = csv.reader(f)
consume(f_reader, 20000000)
raw_data = np.array(list(islice(f_reader,0,10000000)),dtype = int)

或者这可能会更快:

#UNTESTED
f = open("data.csv")
consume(f, 20000000)
f_reader = csv.reader(f)
raw_data = np.array(list(islice(f_reader,0,10000000)),dtype = int)