解析大型压缩xml文件,python

2024-10-04 01:27:03 发布

您现在位置: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

有没有一种方法可以动态解析压缩的bz2xml文件?在

注意:p.Parse(file.read())不是这里的选项。我想解析一个大于可用内存的文件,所以我需要一个流。在


Tags: 文件path代码消息readparsesomexml
3条回答

你能传入一个mmap()的文件吗?这样可以自动分页文件所需的部分,避免内存溢出。当然,如果expat构建了一个解析树,它可能仍然会耗尽内存。在

http://docs.python.org/library/mmap.html

Memory-mapped file objects behave like both strings and like file objects. Unlike normal string objects, however, these are mutable. You can use mmap objects in most places where strings are expected; for example, you can use the re module to search through a memory-mapped file.

只需使用p.ParseFile(file)而不是p.Parse(file)。在

Parse()接受字符串,ParseFile()接受文件句柄,并根据需要读取数据。在

参考号:http://docs.python.org/library/pyexpat.html#xml.parsers.expat.xmlparser.ParseFile

file对象上使用^{}以字符串形式读入整个文件,然后将其传递给Parse?在

file  = BZ2File(SOME_FILE_PATH)
p = xml.parsers.expat.ParserCreate()
p.Parse(file.read())

相关问题 更多 >