By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,854 Members | 2,004 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,854 IT Pros & Developers. It's quick & easy.

Simple UnZip Script, help

P: 34
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:

Expand|Select|Wrap|Line Numbers
  1. import zipfile, os, sys
  2.  
  3. zip1 = ("C:\\Temp\\test11.zip")
  4.  
  5. z = zipfile.ZipFile(zip1, 'r')
  6.  
  7. zList = z.namelist()
  8.  
  9. for zItem in zList:
  10.     print "Unpacking",zItem
  11.     zRead = z.read(zItem)
  12.     z1File = open(zItem,'wb')
  13.     z1File.write(zRead)
  14.     z1File.close
  15. print "finished!"
  16.  

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!
Jul 1 '08 #1
Share this Question
Share on Google+
3 Replies


kaarthikeyapreyan
100+
P: 107
Try this code, hope this suits your requirement.

Expand|Select|Wrap|Line Numbers
  1. import os, sys, zipfile
  2.  
  3. class myzip:
  4.   def __init__(self):
  5.     source = raw_input('Enter the name of the zipfile you want to extract :')
  6.     self.diffdir = raw_input('Enter the name of the dir you want to extract the file if in present dir enter "." :')
  7.     fh = open(source, 'rb')
  8.     self.z = zipfile.ZipFile(fh)
  9.     dirs = []
  10.     for name in self.z.namelist():
  11.       if name.endswith('/'):
  12.         dirs.append(name)
  13.  
  14.     self._checkdiff(dirs)
  15.  
  16.   def _checkdiff(self,dirs):
  17.     """
  18.     Appends if different directory is specified
  19.     """
  20.     for dirname in dirs:
  21.       if self.diffdir == "." :
  22.         self.flag = 0
  23.       else :
  24.         dirname = os.path.join(self.diffdir,dirname)
  25.         self.flag = 1
  26.       self.generatedir(dirname)
  27.     self.generatefiles()
  28.  
  29.   def generatedir(self,dirname):
  30.     """
  31.     Generate the directories for our new zip archive
  32.     """
  33.     if not os.path.isdir(dirname):
  34.       os.mkdir(dirname)
  35.     else:
  36.       print "Directory exist"
  37.       sys.exit(1)
  38.  
  39.   def generatefiles(self):
  40.     """
  41.     Write files from archive to existence
  42.     """
  43.     for name in self.z.namelist():
  44.       if self.flag == 1:
  45.         dest = os.path.join(self.diffdir,name)
  46.       if not dest.endswith('/'):
  47.         outfile = open(dest, 'wb')
  48.         outfile.write(self.z.read(name))
  49.         outfile.close()
  50.     self.z.close()
  51.  
  52. obj = myzip()
  53.  
Jul 2 '08 #2

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

Expand|Select|Wrap|Line Numbers
  1. import zipfile, os, sys
  2.  
  3. test1_zip = ("C:\\Temp\\test1.zip")
  4.  
  5. folder_name = sys.argv[1]
  6.  
  7. output_dir = "C:\\Temp\\" + folder_name
  8.  
  9. z = zipfile.ZipFile(test1_zip, 'r')
  10.  
  11. zList = z.namelist()
  12.  
  13. for zItem in zList:
  14.     print "Unpacking",zItem
  15.     zRead = z.read(zItem)
  16.     z1File = open(os.path.join(output_dir, zItem),'wb') 
  17.     z1File.write(zRead)
  18.     z1File.close
  19. print "Finished"
Jul 2 '08 #3

P: 56
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.

Expand|Select|Wrap|Line Numbers
  1. def unzip(src,dst,name=''):
  2.     if not os.path.isfile(src):
  3.         print 'Zip file not found'
  4.     else:
  5.         archive = ZipFile(src,'r')  
  6.         #src = os.path.basename(src)
  7.         if name=='':
  8.             name = os.path.basename(os.path.dirname(dst))
  9.         dst=dst+name+'/'
  10.         for file in archive.namelist():
  11.             try:
  12.                 os.makedirs(normpath((abspath(dst)+'/'+dirname(file))))            
  13.             except:
  14.                 pass
  15.             if not str(normpath((abspath(dst)+'/'+dirname(file)))+"/"+basename(file)).endswith('/'):
  16.                 efile = open(normpath((abspath(dst)+'/'+dirname(file)))+"/"+basename(file),'wb')
  17.                 efile.write(archive.read(file))
  18.                 efile.close()
  19.                 accesstime = time.time()
  20.                 timeTuple=(int(archive.getinfo(file).date_time[0]),\
  21.                            int(archive.getinfo(file).date_time[1]),\
  22.                            int(archive.getinfo(file).date_time[2]),\
  23.                            int(archive.getinfo(file).date_time[3]) ,\
  24.                            int(archive.getinfo(file).date_time[4]),\
  25.                            int(archive.getinfo(file).date_time[5]),\
  26.                            int(0),int(0),int(0))
  27.                 modifiedtime = mktime(timeTuple)
  28.                 try:
  29.                     utime((dst+file), (accesstime,modifiedtime))
  30.                 except:
  31.                     pass
  32.  
  33.         archive.close()
  34.  
Jul 3 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.