解析大型压缩xml文件,python
file = BZ2File(SOME_FILE_PATH)
p = xml.parsers.expat.ParserCreate()
p.Parse(file)
下面的代码尝试解析用 bz2 压缩的 xml 文件。不幸的是,它失败并显示一条消息:
TypeError: Parse() argument 1 must be string or read-only buffer, not bz2.BZ2File
有没有办法动态解析压缩的 bz2 xml 文件?
注意:p.Parse(file.read())
在这里不是一个选项。我想解析一个大于可用内存的文件,所以我需要一个流。
file = BZ2File(SOME_FILE_PATH)
p = xml.parsers.expat.ParserCreate()
p.Parse(file)
Here's code that tries to parse xml file compressed with bz2. Unfortunately it fails with a message:
TypeError: Parse() argument 1 must be string or read-only buffer, not bz2.BZ2File
Is there a way to parse on the fly compressed bz2 xml files?
Note: p.Parse(file.read())
is not an option here. I want to parse a file which is larger than available memory, so I need to have a stream.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需使用 p.ParseFile(file) 而不是 p.Parse(file) 即可。
Parse() 接受一个字符串,ParseFile() 接受一个文件句柄,并根据需要读取数据。
参考: http://docs.python.org/库/pyexpat.html#xml.parsers.expat.xmlparser.ParseFile
Just use p.ParseFile(file) instead of p.Parse(file).
Parse() takes a string, ParseFile() takes a file handle, and reads the data in as required.
Ref: http://docs.python.org/library/pyexpat.html#xml.parsers.expat.xmlparser.ParseFile
使用
.read()
在file
对象上以字符串形式读取整个文件,然后将其传递给Parse
?Use
.read()
on thefile
object to read in the entire file as a string, and then pass that toParse
?你能传入一个 mmap() 的文件吗?这应该负责自动分页文件的所需部分,并避免内存溢出。当然,如果
expat
构建了一个解析树,它仍然可能会耗尽内存。http://docs.python.org/library/mmap.html
Can you pass in an mmap()'ed file? That should take care of automatically paging the needed parts of the file in, and avoid memory overflow. Of course if
expat
builts a parse tree, it might still run out of memory.http://docs.python.org/library/mmap.html