python内存错误
当尝试将大型文本文件加载到内存中时,我得到以下结果:python内存错误,python,memory,Python,Memory,当尝试将大型文本文件加载到内存中时,我得到以下结果: Python(24297,0xa0d291a8) malloc: *** mach_vm_map(size=717418496) failed (error code=3) *** error: can't allocate region *** set a breakpoint in malloc_error_break to debug MemoryError 导致它的代码是: with open('list.txt') as f:
Python(24297,0xa0d291a8) malloc: *** mach_vm_map(size=717418496) failed (error code=3)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
MemoryError
导致它的代码是:
with open('list.txt') as f:
total = sum(1 for _ in f)
有没有一种本地python方法可以解决这个问题?Wild guess:
您正在一个不包含(或很少)换行符的二进制文件上运行上述代码。因此,尝试读取一行会读取一条非常长的行
请尝试以下方法:
with open('list.txt') as f:
total = sum(block.count('\n')
for block in iter(lambda: f.read(64*1024), ''))
你的系统有多少内存?@sapi:这段代码不应该使用生成器,然后不需要将整个文件存储在内存中吗?
wc-l list.txt
可以解决这个问题。在windows系统上呢?文件有多长?@Matt3o12-在你对原始帖子的评论中,你说你创建了110000字节长的行。这相对较短。正在尝试创建没有换行符的1GB文件。例如:dd if=/dev/zero of=/tmp/list.txt bs=1M count=1K
dd:count:非法数值
。无论如何,我现在有了第三个测试用例,它几乎是1GB,python仍然不需要超过20MB。好吧,我现在有一个2GB的文件,只有零,但python只占用了我2GB的内存,但最终崩溃了:SystemError:Negative size从StringAndSize传递给PyString_
。2489971200对于整数来说太大了。无论如何,对于16GB Ram,应该存在内存问题。分块阅读效果很好(而且比我想象的要快)。这很有效,但它打印了5100万行(不仅仅是一行)