簡體   English   中英

64位系統,8GB的RAM,超過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 該文件包含1億行。 但是,更不用說讀取整個文件了,即使讀取前1000萬行也給我一個'MemoryError:'<-這確實是整個錯誤消息。

有人可以告訴我為什么嗎? 另外還有一個問題,有人可以告訴我如何朗讀嗎,比如說2000萬行? 我知道我需要使用f.seek(某個數字),但是由於我的數據是一個csv文件,所以我不知道應該將哪個數字確切地放入f.seek()中,以便它從第20行開始精確讀取。

非常感謝你。

有人可以告訴我如何閱讀,例如說第2千萬行嗎? 我知道我需要使用f.seek(一些數字)

不,在這種情況下,您不能(也不能)使用f.seek() 相反,您必須以某種方式讀取前兩千萬行中的每一行。

Python文檔具有以下配方:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM