首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python:如何在Python中读取压缩的7z文件中的一行?

Python:如何在Python中读取压缩的7z文件中的一行?
EN

Stack Overflow用户
提问于 2015-12-07 22:10:50
回答 1查看 867关注 0票数 0

我有一个多GB的7z归档,其中包含一个xml文件。我希望从这个压缩文件中一次读取一行,直到在Python3.4上达到它(文件)的EOF。我不能把它解压缩成它的完整大小,大约是几to。

有人建议我使用很多库,比如pylzmalzma,但它们不支持7z格式。libarchive确实支持7z,但它是以块为单位读取的,我认为这不一定是文件中的文本行。

请提供建议。谢谢。

EN

回答 1

Stack Overflow用户

发布于 2015-12-07 23:03:49

(详述yield部分)注意,我不知道这个库,也不知道您使用什么函数来获取未压缩数据块。但我的意思是这样的:

代码语言:javascript
复制
def 7zreadline(filename):
    with open(filename, 'rb') as fh: #automatically closes filehandler when finished
        archive = py7zlib.Archive7z(fh)
        current_line = ''
        for block in archive.getblock(): #I do not know how you get a block of uncompressed data, so I ''abstract'' the call, you get the idea...
            current_line += block
            while '\n' in current_line:
                yield current_line[:current_line.index('\n')+1] # gives all until '\n' to the caller
                current_line = current_line[current_line.index('\n')+1:] # now, initialize current_line with the rest of your block.
        yield current_line #return the end of file

然后你可以像这样使用它:

代码语言:javascript
复制
for line in 7zreadline('myfile.zip'):
    print(line)

如果知道这个库的人可以得到一些正确的东西,欢迎进行编辑。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34135592

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档