How to unzip a file with Python 2.4?

后端 未结 5 697
旧巷少年郎
旧巷少年郎 2020-12-08 09:42

I\'m having a hard time figuring out how to unzip a zip file with 2.4. extract() is not included in 2.4. I\'m restricted to using 2.4.4 on my server.

Ca

相关标签:
5条回答
  • 2020-12-08 10:22

    Not fully tested, but it should be okay:

    import os
    from zipfile import ZipFile, ZipInfo
    
    class ZipCompat(ZipFile):
        def __init__(self, *args, **kwargs):
            ZipFile.__init__(self, *args, **kwargs)
    
        def extract(self, member, path=None, pwd=None):
            if not isinstance(member, ZipInfo):
                member = self.getinfo(member)
            if path is None:
                path = os.getcwd()
            return self._extract_member(member, path)
    
        def extractall(self, path=None, members=None, pwd=None):
            if members is None:
                members = self.namelist()
            for zipinfo in members:
                self.extract(zipinfo, path)
    
        def _extract_member(self, member, targetpath):
            if (targetpath[-1:] in (os.path.sep, os.path.altsep)
                and len(os.path.splitdrive(targetpath)[1]) > 1):
                targetpath = targetpath[:-1]
            if member.filename[0] == '/':
                targetpath = os.path.join(targetpath, member.filename[1:])
            else:
                targetpath = os.path.join(targetpath, member.filename)
            targetpath = os.path.normpath(targetpath)
            upperdirs = os.path.dirname(targetpath)
            if upperdirs and not os.path.exists(upperdirs):
                os.makedirs(upperdirs)
            if member.filename[-1] == '/':
                if not os.path.isdir(targetpath):
                    os.mkdir(targetpath)
                return targetpath
            target = file(targetpath, "wb")
            try:
                target.write(self.read(member.filename))
            finally:
                target.close()
            return targetpath
    
    0 讨论(0)
  • 2020-12-08 10:30

    You have to use namelist() and extract(). Sample considering directories

    import zipfile
    import os.path
    import os
    zfile = zipfile.ZipFile("test.zip")
    for name in zfile.namelist():
      (dirname, filename) = os.path.split(name)
      print "Decompressing " + filename + " on " + dirname
      if not os.path.exists(dirname):
        os.makedirs(dirname)
      zfile.extract(name, dirname)
    
    0 讨论(0)
  • 2020-12-08 10:32

    I am testing in Python 2.7.3rc2 and the the ZipFile.namelist() is not returning an entry with just the sub directory name for creating a sub directory, but only a list of file names with sub directory, as follows:

    ['20130923104558/control.json', '20130923104558/test.csv']

    Thus the check

    if fileName == '':

    does not evaluate to True at all.

    So I modified the code to check if the dirName exists inside destDir and to create dirName if it does not exist. File is extracted only if fileName part is not empty. So this should take care of the condition where a directory name can appear in ZipFile.namelist()

    def unzip(zipFilePath, destDir):
        zfile = zipfile.ZipFile(zipFilePath)
        for name in zfile.namelist():
            (dirName, fileName) = os.path.split(name)
            # Check if the directory exisits
            newDir = destDir + '/' + dirName
            if not os.path.exists(newDir):
                os.mkdir(newDir)
            if not fileName == '':
                # file
                fd = open(destDir + '/' + name, 'wb')
                fd.write(zfile.read(name))
                fd.close()
        zfile.close()
    
    0 讨论(0)
  • 2020-12-08 10:36

    There's some problem with Vinko's answer (at least when I run it). I got:

    IOError: [Errno 13] Permission denied: '01org-webapps-countingbeads-422c4e1/'
    

    Here's how to solve it:

    # unzip a file
    def unzip(path):
        zfile = zipfile.ZipFile(path)
        for name in zfile.namelist():
            (dirname, filename) = os.path.split(name)
            if filename == '':
                # directory
                if not os.path.exists(dirname):
                    os.mkdir(dirname)
            else:
                # file
                fd = open(name, 'w')
                fd.write(zfile.read(name))
                fd.close()
        zfile.close()
    
    0 讨论(0)
  • 2020-12-08 10:44

    Modifying Ovilia's answer so that you can specify the destination directory as well:

    def unzip(zipFilePath, destDir):
        zfile = zipfile.ZipFile(zipFilePath)
        for name in zfile.namelist():
            (dirName, fileName) = os.path.split(name)
            if fileName == '':
                # directory
                newDir = destDir + '/' + dirName
                if not os.path.exists(newDir):
                    os.mkdir(newDir)
            else:
                # file
                fd = open(destDir + '/' + name, 'wb')
                fd.write(zfile.read(name))
                fd.close()
        zfile.close()
    
    0 讨论(0)
提交回复
热议问题