首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用PyLZMA的示例

使用PyLZMA的示例
EN

Stack Overflow用户
提问于 2012-05-22 19:53:48
回答 2查看 15.9K关注 0票数 13

我想使用PyLZMA从归档文件(例如test.7z)中提取一个文件,然后将其提取到相同的目录中。

我是Python的新手,不知道如何开始。我做了一些谷歌搜索,找到了some examplesdocs,但我不明白它们是如何工作的。

有没有人可以把我想要做的事情的基本代码贴出来,这样我就可以开始工作和理解了?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-09-06 11:32:17

下面是一个处理基本功能的Python类。我已经将它用于我自己的工作:

代码语言:javascript
复制
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()
票数 14
EN

Stack Overflow用户

发布于 2012-06-01 07:01:46

下面是我在http://www.linuxplanet.org/blogs/?cat=3845找到的两个代码片段

代码语言:javascript
复制
# 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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10701528

复制
相关文章

相似问题

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