Python – 将非常大(6.4GB)的XML文件转换为JSON

基本上,我有一个6.4GB的
XML文件,我想将其转换为
JSON,然后将其保存到磁盘.我目前正在使用i7 2700k和16GB的ram运行OSX 10.8.4,并运行
Python 64bit(双重检查).我收到一个错误,我没有足够的内存来分配.我该如何解决这个问题?

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.iterparse和xml.sax.parse.这些函数通常称为“XML Stream Parser”.

您使用的xmltodict库也具有流模式.我认为它可以解决你的问题

https://github.com/martinblech/xmltodict#streaming-mode

dawei

【声明】:淮南站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。