【发布时间】:2017-05-04 01:52:09
【问题描述】:
我是 Python 的新手。从两个文件加载两个字典时出现内存错误。这两个文件是
with open(filename, 'rb') as f:
hashtable_album = {}
for line in f:
# print i
p = 0
q = line.find("####")
# print p
# print q
itembuf = line[p:q]
# print itembuf
dictbuf = line[q + 4:-1]
# print line
a = json.loads(dictbuf)
# print a
# print type(a)
hashtable_album[itembuf] = a
f.close()
with open(filename2, 'rb') as f2:
hashtable_item={}
i=0
for line in f:
print len(dic)
print i
#print line
p = 0
q = line.find("####")
# print p
# print q
itembuf = line[p:q]
# print itembuf
dictbuf = line[q + 4:-1]
# print line
a = json.loads(dictbuf)
#print a
# print type(a)
hashtable_item[itembuf] = a
i=i+1
f2.close()
第一个文件大约 400MB,比第二个大,大约 200MB,我可以成功加载第一个文件。但是当我加载第二个文件时,我得到了内存错误
Traceback (most recent call last):
File "E:/py_workspace/1.0_memory_error.py", line 44, in <module>
hashtable_item[itembuf] = a
MemoryError
如果我更改顺序以首先将文件加载为读取文件2,然后再加载文件1,则在加载第二个文件时也会出现内存错误。 我猜内存错误来自字典,所以我在加载 file1 后清除了字典
hashtable_album = {}
然后继续加载file2。这次它没有内存错误。 但我需要同时使用这两个字典。那么如何将它们一起加载呢?
提示:我尝试使用 cPickle 来保存 dict,但它无法正常工作,并且我也遇到了内存错误。
【问题讨论】:
-
同一脚本中的数据容器和比较器,是个非常糟糕的主意!对您很重要的数据,您保存在某处,但
why don't use any database system ?直接IO总是引发错误(出现硬件性能错误)。您是否在“虚拟操作系统”下运行此代码?
标签: python json file out-of-memory reader