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,我使用的是具有 8GB RAM 的 64 位系统。该文件包含 1 亿行。然而,更不用说读取整个文件了,即使读取前 1000 万行也会给我一个“MemoryError:” <- 这实际上是整个错误消息。
有人可以告诉我为什么吗?另外作为一个附带问题,有人可以告诉我如何阅读,比如说第 2000 万行吗?我知道我需要使用 f.seek(某个数字),但由于我的数据是一个 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)
关于python - 64 位系统,8GB 内存,略多于 800MB 的 CSV,用 python 读取会出现内存错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30404256/