Python将2GB的文本文件加载到内存中

2024-04-27 07:18:44 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python2.7中,当我将2.5GB文本文件中的所有数据加载到内存中以便更快地进行以下处理时:

>>> f = open('dump.xml','r')
>>> dump = f.read()

我得到以下错误:

Python(62813) malloc: *** mmap(size=140521659486208) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
MemoryError

Python为什么要为2563749237字节的数据分配140521659486208字节的内存?如何修复代码以使其加载所有字节?

我有大约3GB的内存空闲。该文件是一个Wiktionary xml转储文件。


Tags: 文件数据内存inread字节错误error
2条回答

根据一些快速的谷歌搜索,我发现this forum post似乎解决了您似乎遇到的问题。假设您运行的是基于错误代码的Mac或Linux,您可以尝试使用论坛帖子中建议的gc.enable()gc.collect()来实现垃圾收集。

如果使用mmap,则可以立即将整个文件加载到内存中。

import mmap

with open('dump.xml', 'rb') as f:
  # Size 0 will read the ENTIRE file into memory!
  m = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ) #File is open read-only

  # Proceed with your code here -- note the file is already in memory
  # so "readine" here will be as fast as could be
  data = m.readline()
  while data:
    # Do stuff
    data = m.readline()

相关问题 更多 >