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: - 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!
3 2154
Try this code, hope this suits your requirement. - 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()
-
Thanks, that is helpful, especially for future use. For my specifc/current needs, I went with this: - 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"
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. -
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()
-
Sign in to post your reply or Sign up for a free account.
Similar topics |
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...
|
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...
|
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...
|
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)
|
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****
| |
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
|
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")
|
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.
|
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.
|
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...
|
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...
| |
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...
|
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,...
|
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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| | |