473,396 Members | 1,891 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Simple UnZip Script, help

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
3 2143
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
jld730
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
heiro
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

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

Similar topics

3
by: Jim | last post by:
I have a user who works remotely who just does not understand the concept of zipping and unzipping files no matter how many times I explain it. I need to create something for her that will do the...
6
by: Jim M | last post by:
I've been distributing a fairly mature, very specific MS Access application to end users in small offices of colleges for several years now. This is a part-time venture and low volume operation-...
2
by: mihai123 | last post by:
I have a blob column with zips files (there are open office documents). Can I unzip the files in the column without create the file? or i need to create the file first. Is there a class with zip...
0
by: Rocky Zhou | last post by:
python unzip At first, I tried to use 'os.popen3("unzip ...") like this: fin, fout, ferr = os.popen3("unzip -o -d %s %s" % (dest, zipfile)) strerr = ferr.read() # This makes the program hanging...
3
by: sdoty044 | last post by:
I am a true n00b... and I just using Python to complete some very small uneventful task, but need help with one last thing. Basically, this I what I am trying to do. make a temp directory...
5
by: =?Utf-8?B?anVsaW8=?= | last post by:
Hi, I write a program to unzip a Tar file generated on a Unix environment file using SharpZipLib, but returns a error "Header checksum is invalid" when execute the program. This error appears...
5
by: noydb | last post by:
Can someone help me with this script, which I found posted elsewhere? I'm trying to figure out what is going on here so that I can alter it for my needs, but the lack of descriptive names is making...
1
by: olddocks | last post by:
I want to upload a zip file and then extract/unzip it. I am accomplishing this with php exec command. I am calling unzip from php exec command within a php script and it is not extracting files. why?...
2
by: somsub | last post by:
Hi all, Here is my samle code use strict ; use warnings ; use IO::Uncompress::Unzip ; When I compiled this three lines of code in win32 I got error like below.
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.