首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何读取用7z压缩的文本文件?

如何读取用7z压缩的文本文件?
EN

Stack Overflow用户
提问于 2013-11-21 02:52:05
回答 3查看 9.6K关注 0票数 12

我想从一个压缩为7z的csv (文本)文件中逐行读取(在Python2.7中)。我不想解压缩整个(大)文件,而是对行进行流式处理。

我尝试了pylzma.decompressobj(),但没有成功。我得到一个数据错误。请注意,此代码尚未逐行读取:

代码语言:javascript
复制
input_filename = r"testing.csv.7z"
with open(input_filename, 'rb') as infile:
    obj = pylzma.decompressobj()
    o = open('decompressed.raw', 'wb')
    obj = pylzma.decompressobj()
    while True:
        tmp = infile.read(1)
        if not tmp: break
        o.write(obj.decompress(tmp))
    o.close()

输出:

代码语言:javascript
复制
    o.write(obj.decompress(tmp))
ValueError: data error during decompression
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-11-21 05:59:27

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

在这个时间点(pylzma-0.5.0),py7zlib模块还没有实现一个允许以字节流或字符流的形式读取存档成员的接口-它的ArchiveFile类只提供了一个read()函数,该函数可以一次解压缩并返回成员中所有未压缩的数据。考虑到这一点,可以做的最好的事情就是通过Python生成器迭代返回字节或行,并将其用作缓冲区。

以下是后一种方法,但如果问题是存档成员文件本身很大,则可能没有帮助。

下面的代码应该可以在Python 3.x和2.7中运行。

代码语言:javascript
复制
import io
import os
import py7zlib


class SevenZFileError(py7zlib.ArchiveError):
    pass

class 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 '\r\n' 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().decode()
        for line in io.StringIO(data, newline=newline):
            yield line


if __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))
票数 8
EN

Stack Overflow用户

发布于 2013-11-21 02:58:32

如果您使用的是Python 3.3+,则可以使用在该版本的标准库中添加的lzma模块来完成此操作。

请参阅:lzma

票数 1
EN

Stack Overflow用户

发布于 2020-07-21 19:28:55

如果你可以使用Python3,有一个有用的库py7zr,它支持的部分 7zip解压缩,如下所示:

代码语言:javascript
复制
import py7zr
import re
filter_pattern = re.compile(r'<your/target/file_and_directories/regex/expression>')
with SevenZipFile('archive.7z', 'r') as archive:
    allfiles = archive.getnames()
    selective_files = [f if filter_pattern.match(f) for f in allfiles]
    archive.extract(targets=selective_files)
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20104460

复制
相关文章

相似问题

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