gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:16:35 24 4
gpt4 key购买 nike

在 Python 2.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 的空闲内存。该文件是维基词典 xml 转储。

最佳答案

如果您使用 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()

关于Python 将 2GB 的文本文件加载到内存中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11159077/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com