实际上,我有一个6.4GB的XML文件,我想转换成JSON,然后将其保存到磁盘上。我目前运行的是OSX 10.8.4,带有I7 2700K和16Gbs的RAM,运行的是python 64位(双重检查)。我有一个错误,我没有足够的内存来分配。我该怎么修理这个?

print 'Opening'
f = open('large.xml', 'r')
data = f.read()
f.close()

print 'Converting'
newJSON = xmltodict.parse(data)

print 'Json Dumping'
newJSON = json.dumps(newJSON)

print 'Saving'
f = open('newjson.json', 'w')
f.write(newJSON)
f.close()

错误:
Python(2461) malloc: *** mmap(size=140402048315392) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
Traceback (most recent call last):
  File "/Users/user/Git/Resources/largexml2json.py", line 10, in <module>
    data = f.read()
MemoryError

最佳答案

许多Python XML库支持增量分析XML子元素,例如标准库中的xml.etree.ElementTree.iterparsexml.sax.parse。这些函数通常称为“XML流解析器”。
您使用的xmltodict库也具有流模式。我想它可以解决你的问题
https://github.com/martinblech/xmltodict#streaming-mode

09-04 15:13