Example of how to use PyLZMA

Philipp Bammes picture Philipp Bammes · May 22, 2012 · Viewed 15.3k times · Source

I want to use PyLZMA to extract a file from an archive (e.g. test.7z) and extract it to the same directory.

I'm a newbie to Python and have no idea how to start. I've done some googling and found some examples and docs, but I don't understand how they work.

Could someone please post the basic code for what I want to do so that I can start to work and understand?

Answer

Brian B picture Brian B · Sep 6, 2012

Here is a Python class to handle the basic functionality. I have used it for my own work:

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()