Simple UnZip Script, help

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jld730
    New Member
    • Apr 2007
    • 34

    Simple UnZip Script, help

    Hi All,

    I am looking for help on this simple script to unzip/extract the contents of a zip file. This is what I have so far:

    Code:
    import zipfile, os, sys
    
    zip1 = ("C:\\Temp\\test11.zip")
    
    z = zipfile.ZipFile(zip1, 'r')
    
    zList = z.namelist()
    
    for zItem in zList:
        print "Unpacking",zItem
        zRead = z.read(zItem)
        z1File = open(zItem,'wb')
        z1File.write(zRead)
        z1File.close
    print "finished!"

    I had the unzipping working, but not anymore. As is, the script executes w/o error, but doesn't unzip the files. Also, how would you unzip the file to a different directory? Is there a better way to do this then what I'm doing? I got much of this code from a post elsewhere, but am not too sure I follow it.

    Thanks!
  • kaarthikeyapreyan
    New Member
    • Apr 2007
    • 106

    #2
    Try this code, hope this suits your requirement.

    Code:
    import os, sys, zipfile
    
    class myzip:
      def __init__(self):
        source = raw_input('Enter the name of the zipfile you want to extract :')
        self.diffdir = raw_input('Enter the name of the dir you want to extract the file if in present dir enter "." :')
        fh = open(source, 'rb')
        self.z = zipfile.ZipFile(fh)
        dirs = []
        for name in self.z.namelist():
          if name.endswith('/'):
            dirs.append(name)
            
        self._checkdiff(dirs)
        
      def _checkdiff(self,dirs):
        """
        Appends if different directory is specified
        """
        for dirname in dirs:
          if self.diffdir == "." :
            self.flag = 0
          else :
            dirname = os.path.join(self.diffdir,dirname)
            self.flag = 1
          self.generatedir(dirname)
        self.generatefiles()
        
      def generatedir(self,dirname):
        """
        Generate the directories for our new zip archive
        """
        if not os.path.isdir(dirname):
          os.mkdir(dirname)
        else:
          print "Directory exist"
          sys.exit(1)
      
      def generatefiles(self):
        """
        Write files from archive to existence
        """
        for name in self.z.namelist():
          if self.flag == 1:
            dest = os.path.join(self.diffdir,name)
          if not dest.endswith('/'):
            outfile = open(dest, 'wb')
            outfile.write(self.z.read(name))
            outfile.close()
        self.z.close()
    
    obj = myzip()

    Comment

    • jld730
      New Member
      • Apr 2007
      • 34

      #3
      Thanks, that is helpful, especially for future use. For my specifc/current needs, I went with this:

      Code:
      import zipfile, os, sys
      
      test1_zip = ("C:\\Temp\\test1.zip")
      
      folder_name = sys.argv[1]
      
      output_dir = "C:\\Temp\\" + folder_name
      
      z = zipfile.ZipFile(test1_zip, 'r')
      
      zList = z.namelist()
      
      for zItem in zList:
          print "Unpacking",zItem
          zRead = z.read(zItem)
          z1File = open(os.path.join(output_dir, zItem),'wb') 
          z1File.write(zRead)
          z1File.close
      print "Finished"

      Comment

      • heiro
        New Member
        • Jul 2007
        • 56

        #4
        Hi,

        if you want to preserve the time stamp of the file you can also use this code.
        This can also unpack zip files with folders.

        Code:
        def unzip(src,dst,name=''):
            if not os.path.isfile(src):
                print 'Zip file not found'
            else:
                archive = ZipFile(src,'r')  
                #src = os.path.basename(src)
                if name=='':
                    name = os.path.basename(os.path.dirname(dst))
                dst=dst+name+'/'
                for file in archive.namelist():
                    try:
                        os.makedirs(normpath((abspath(dst)+'/'+dirname(file))))            
                    except:
                        pass
                    if not str(normpath((abspath(dst)+'/'+dirname(file)))+"/"+basename(file)).endswith('/'):
                        efile = open(normpath((abspath(dst)+'/'+dirname(file)))+"/"+basename(file),'wb')
                        efile.write(archive.read(file))
                        efile.close()
                        accesstime = time.time()
                        timeTuple=(int(archive.getinfo(file).date_time[0]),\
                                   int(archive.getinfo(file).date_time[1]),\
                                   int(archive.getinfo(file).date_time[2]),\
                                   int(archive.getinfo(file).date_time[3]) ,\
                                   int(archive.getinfo(file).date_time[4]),\
                                   int(archive.getinfo(file).date_time[5]),\
                                   int(0),int(0),int(0))
                        modifiedtime = mktime(timeTuple)
                        try:
                            utime((dst+file), (accesstime,modifiedtime))
                        except:
                            pass
                                
                archive.close()

        Comment

        Working...