如何使用PyLZMA的示例

13
我希望使用PyLZMA从存档文件(例如test.7z)中提取文件并将其提取到同一目录中。
作为Python的新手,我不知道该如何开始。我已经搜索了一些示例文档,但我不理解它们是如何工作的。
请有人发布我想要做的基本代码,以便我可以开始工作并理解?

4
你能展示一些你尝试过但失败了的例子吗?请简要说明尝试方法,但不要解释。 - Levon
1
看起来这个库确实完全没有文档,除了一些类似于class Base(object): """base oject"""的docstrings... - Fred Foo
1
这里的人通常不喜欢“给我代码”的问题,尽量展示一些努力,告诉我们你找到了什么,尝试了什么,以及你缺少什么,这样你会得到更好的支持。 - KurzedMetal
我找到了以下内容: https://github.com/fancycode/pylzma/blob/master/doc/usage.txt 这里有一些例子:http://nullege.com/codes/search/pylzma.decompress 我尝试了以下代码: `f = Archive7z(open('test.7z', 'rb'))f.list()`它显示了存档的内容,但我不知道如何告诉Python去解压缩它。(我会继续自己寻找解决方案) - Philipp Bammes
当你不知道从哪里开始时,我建议你下载软件包源代码并检查是否有一个“test”目录。通常这是一些简单的代码,会帮助你入门 :) - user3672754
2个回答

15

这是一个处理基本功能的Python类。我已经用它来完成我的工作:

import py7zlib
class SevenZFile(object):
    @classmethod
    def is_7zfile(cls, filepath):
        '''
        Class method: determine if file path points to a valid 7z archive.
        '''
        is7z = False
        fp = None
        try:
            fp = open(filepath, 'rb')
            archive = py7zlib.Archive7z(fp)
            n = len(archive.getnames())
            is7z = True
        finally:
            if fp:
                fp.close()
        return is7z

    def __init__(self, filepath):
        fp = open(filepath, 'rb')
        self.archive = py7zlib.Archive7z(fp)

    def extractall(self, path):
        for name in self.archive.getnames():
            outfilename = os.path.join(path, name)
            outdir = os.path.dirname(outfilename)
            if not os.path.exists(outdir):
                os.makedirs(outdir)
            outfile = open(outfilename, 'wb')
            outfile.write(self.archive.getmember(name).read())
            outfile.close()

2
警告:目前的Archive7z将整个内容解压到内存中以读取文件...所以在我的情况下,一个10 MB的文件在内存中变成了1.2 GB。 - liquidpele

3

我在这里找到了两个代码片段 http://www.linuxplanet.org/blogs/?cat=3845

# Compress the input file (as a stream) to a file (as a stream)
i = open(source_file, 'rb')
o = open(compressed_file, 'wb')
i.seek(0)
s = pylzma.compressfile(i)
while True:
    tmp = s.read(1)
    if not tmp: break
    o.write(tmp)
o.close()
i.close()

# Decomrpess the file (as a stream) to a file (as a stream)
i = open(compressed_file, 'rb')
o = open(decompressed_file, 'wb')
s = pylzma.decompressobj()
while True:
    tmp = i.read(1)
    if not tmp: break
    o.write(s.decompress(tmp))
o.close()
i.close()

3
类似的片段已经在github.com/fancycode/pylzma/blob/master/doc/usage.txt中了;同时,在解压缩情况下应该注意s.flush()。(不过,不知怎么的,谷歌搜索总是先引导到这里,呵呵) - HoverHell
由于 OP 想要从存档中提取文件,我认为这个回答并没有解答问题,并且惊讶它竟然得到了赞同。 - martineau
2
usage.txt --> usage.md @ https://github.com/fancycode/pylzma/blob/master/doc/USAGE.md - philshem
linuxplanet.org已经成为一只死鹦鹉。 - rossmcm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接