栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何从7z压缩的文本文件中读取?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何从7z压缩的文本文件中读取?

这将允许您迭代行。它部分源自我在另一个问题的答案中找到的一些代码。

在该时间点(

pylzma-0.5.0
),该
py7zlib
模块未实现允许将存档成员作为字节流或字符流读取的API-其
ArchiveFile
类仅提供了一次
read()
解压缩并返回成员中未压缩数据的功能。鉴于此,最好的办法是通过Python生成器使用该缓冲区作为缓冲区迭代地返回字节或行。

下面是后者的操作,但是如果问题是存档 成员 文件本身很大,则可能没有帮助。

下面的代码应在Python 3.x和2.7中均可使用。

import ioimport osimport py7zlibclass SevenZFileError(py7zlib.ArchiveError):    passclass SevenZFile(object):    @classmethod    def is_7zfile(cls, filepath):        """ Determine if filepath points to a valid 7z archive. """        is7z = False        fp = None        try: fp = open(filepath, 'rb') archive = py7zlib.Archive7z(fp) _ = len(archive.getnames()) is7z = True        finally: if fp: fp.close()        return is7z    def __init__(self, filepath):        fp = open(filepath, 'rb')        self.filepath = filepath        self.archive = py7zlib.Archive7z(fp)    def __contains__(self, name):        return name in self.archive.getnames()    def readlines(self, name, newline=''):        r""" Iterator of lines from named archive member.        `newline` controls how line endings are handled.        It can be None, '', 'n', 'r', and 'rn' and works the same way as it does        in StringIO. Note however that the default value is different and is to enable        universal newlines mode, but line endings are returned untranslated.        """        archivefile = self.archive.getmember(name)        if not archivefile: raise SevenZFileError('archive member %r not found in %r' % (name, self.filepath))        # Decompress entire member and return its contents iteratively.        data = archivefile.read().depre()        for line in io.StringIO(data, newline=newline): yield lineif __name__ == '__main__':    import csv    if SevenZFile.is_7zfile('testing.csv.7z'):        sevenZfile = SevenZFile('testing.csv.7z')        if 'testing.csv' not in sevenZfile: print('testing.csv is not a member of testing.csv.7z')        else: reader = csv.reader(sevenZfile.readlines('testing.csv')) for row in reader:     print(', '.join(row))


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/624826.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号