473,602 Members | 2,764 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Simple UnZip Script, help

34 New Member
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 2154
kaarthikeyapreyan
107 New Member
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 New Member
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 New Member
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
4525
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 following: * She receives an outlook message with a zipped file and opens the message. * She opens an Access "Utilities" database and clicks a button labeled "Unzip updated database from eMail message" * Somehow the code behind the button...
6
2028
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- this is somewhat of a hobby for me. Many of my end users are computer phobic and get little support from their IT departments. It is a split database so the datafile gets put on the file server and the 3 different front ends get put on each local...
2
1612
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 function that i can include in my script without a need to change the configuration in php.ini ? I want to unzip just a file named content.xml is that possible? And the last question is there an example of convert XML into HTML i didn't need...
0
1661
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 up if strerr: print >sys.stderr, strerr outlog.error(strerr)
3
2623
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 (this part I can do) Need help with: ***unzip a JAR file with the complete list of subdirectories w/ files****
5
7034
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 when I try to extract the files. Can any help me where is a sample to unzip a tar file TIA Julio
5
1424
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 it difficult. And, the script doesn't quite do anything worthwhile -- it unzips one file from a zipfile, not all files in a zipfile. *** import zipfile, os, sys, glob os.chdir("C:\\Temp")
1
8513
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? <?php echo exec('unzip file.zip'); ?> i checked apache logs and it says It works perfectly fine when i unzip using SSH command line.. how to fix this problem.
2
6374
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
7993
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8401
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8404
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8054
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
5440
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3944
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2418
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1510
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1254
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.