467,888 Members | 1,358 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 467,888 developers. It's quick & easy.

ZIP files

Hi!
I'm beginning to use the zipfile module in Python and I'm confused
about something. I am trying to extract certain files from one zip and
copy them into another one. This is the code I‘ve got so far:
import string
import os, re
from zipfile import *
path= raw_input("\n Please enter the zipfile to be copied: ")

new_zip= ZipFile('something.zip', 'w')
orig_zip=ZipFile(path, 'r')
zip_files= orig_zip.namelist()
for file in zip_files:
if file[-2:] == '.c' or file[-2:] == '.h' or file[-4:] == '.exe':
tempfile = open(file,'w')
x = orig_zip.read(file)
tempfile.write(x)
tempfile.close()
new_zip.write(file)

So far, this code does the work, but I think it's to much work for
just copying entire files…Is there any other way to do this????
Basically, what I want to do is create a copy of the zip but with a
different name…thanks in advance, Oriana
Jul 18 '05 #1
  • viewed: 1690
Share:
8 Replies
Oriana wrote:
I'm beginning to use the zipfile module in Python and I'm confused
about something. I am trying to extract certain files from one zip and
copy them into another one. This is the code I‘ve got so far: [copied by writing to temporary files]
So far, this code does the work, but I think it's to much work for
just copying entire files…Is there any other way to do this????


How about a function like:

import os.path, zipfile

def copy_zip(source_name, dest_name, extensions):
source = zipfile.ZipFile(source_name, 'r')
dest = zipfile.ZipFile(dest_name, 'w', zipfile.ZIP_DEFLATED)
for name in source.namelist():
if os.path.splitext(name)[1].lower() in extensions:
contents = source.read(name)
dest.writestr(name, contents)
dest.close()
source.close()

copy_zip('source.zip', 'dest.zip', {'.c':1, '.h':1, '.exe':1})

If this does the trick for you, try to figure out why you didn't
find "writestr" in the zipfile document. Let us know how we might
improve the document so that we can save work for the next guy.

--Scott David Daniels
Sc***********@Acm.Org
Jul 18 '05 #2
On 10 Nov 2004 08:05:28 -0800, or**********@thalesesec.com (Oriana)
wrote:
Hi!
I'm beginning to use the zipfile module in Python and I'm confused
about something. I am trying to extract certain files from one zip and
copy them into another one. This is the code I‘ve got so far:
import string
import os, re
from zipfile import *
path= raw_input("\n Please enter the zipfile to be copied: ")

new_zip= ZipFile('something.zip', 'w')
orig_zip=ZipFile(path, 'r')
zip_files= orig_zip.namelist()
for file in zip_files:
if file[-2:] == '.c' or file[-2:] == '.h' or file[-4:] == '.exe': # don't do it like this ^^^
if os.path.splitext(file)[1] in ['.c','.h','.exe',]:
# this code is cleaner ^^^ tempfile = open(file,'w')
x = orig_zip.read(file)
tempfile.write(x)
tempfile.close()
new_zip.write(file)

So far, this code does the work, but I think it's to much work for
just copying entire files…Is there any other way to do this????
Basically, what I want to do is create a copy of the zip but with a
different name…thanks in advance, Oriana


if you want a copy of the zip as is then:

def filecopy(infile, outfile):
i = open(infile, "rb")
o = open(outfile, "wb")
while 1:
s = i.read(8192)
if not s:
break
o.write(s)

You might wish to try using a larger buffer than 8192 bytes. BTW,
note that Python automatically closes the files since the file objects
are released when the function returns.

Finally, if you can assume that the files are not huge, why not try
the following one-liner instead:

open(outfile, "wb").write(open(infile, "rb").read())
if you want to copy certain files from the sourceZIP to a targetZIP
this does not work and you were doing it about right.

cheerz,
Ivo.
Jul 18 '05 #3
Ivo Woltring <Py****@IvoNet.nl> writes:
On 10 Nov 2004 08:05:28 -0800, or**********@thalesesec.com (Oriana)
You might wish to try using a larger buffer than 8192 bytes. BTW,
note that Python automatically closes the files since the file objects
are released when the function returns.


This behavior of file objects isn't guaranteed and doesn't happen in
Jython. It's better - and more pythonic - to explicitly close files.

After all, explicit is better than implicit.

<mike
--
Mike Meyer <mw*@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Jul 18 '05 #4
Mike Meyer <mw*@mired.org> wrote in message news:<x7************@guru.mired.org>...
Ivo Woltring <Py****@IvoNet.nl> writes:
On 10 Nov 2004 08:05:28 -0800, or**********@thalesesec.com (Oriana)
You might wish to try using a larger buffer than 8192 bytes. BTW,
note that Python automatically closes the files since the file objects
are released when the function returns.


This behavior of file objects isn't guaranteed and doesn't happen in
Jython. It's better - and more pythonic - to explicitly close files.

After all, explicit is better than implicit.

<mike


Hmmm... does this mean that

open(filename, 'w').write(filedata)

is unsafe ? It's so much more convenient when the object is only going
to be used for the single action.

Regards,

Fuzzy
http://www.voidspace.org.uk/atlantib...thonutils.html
Jul 18 '05 #5
Michael Foord <fu******@gmail.com> wrote:
Hmmm... does this mean that

open(filename, 'w').write(filedata)

is unsafe ? It's so much more convenient when the object is only going
to be used for the single action.


It's not exactly unsafe -- but you do risk, depending on what
implementation of Python you're dealing with, that the file object will
just stay open until some unknown time in the future (no later than the
end of your program's run;-). This may potentially lead to problems if
your program is long-running or open lots of files, etc.

def write_data(filename, data, flags='w'):
fileobject = open(filename, flags)
try: fileobject.write(data)
finally: fileobject.close()

needs to be coded once, and then makes the operation just as convenient
as doing it inline...
Alex
Jul 18 '05 #6
al*****@yahoo.com (Alex Martelli) writes:
Michael Foord <fu******@gmail.com> wrote:
Hmmm... does this mean that

open(filename, 'w').write(filedata)

is unsafe ? It's so much more convenient when the object is only going
to be used for the single action.


It's not exactly unsafe -- but you do risk, depending on what
implementation of Python you're dealing with, that the file object will
just stay open until some unknown time in the future (no later than the
end of your program's run;-). This may potentially lead to problems if
your program is long-running or open lots of files, etc.

def write_data(filename, data, flags='w'):
fileobject = open(filename, flags)
try: fileobject.write(data)
finally: fileobject.close()

needs to be coded once, and then makes the operation just as convenient
as doing it inline...


I'd suggest to expand this a bit, and make it working correctly on
windows too, where binary files must be opened with the 'b' flag:

def _write_data(filename, data, flags):
fileobject = open(filename, flags)
try: fileobject.write(data)
finally: fileobject.close()

def write_data(filename, data, flags="wb"):
_write_data(filename, data, flags)

def write_text(filename, text, flags="w"):
_write_data(filename, data, flags)

plus the corresponding read_data() and read_text() functions.
Hm, add an encoding for unicode, maybe...
Cookbook recipe, or standard lib?

Thomas
Jul 18 '05 #7
Thomas Heller <th*****@python.net> wrote:
...
def write_data(filename, data, flags='w'):
fileobject = open(filename, flags)
try: fileobject.write(data)
finally: fileobject.close()

needs to be coded once, and then makes the operation just as convenient
as doing it inline...
I'd suggest to expand this a bit, and make it working correctly on
windows too, where binary files must be opened with the 'b' flag:


Hmmm, I thought the optional flags parm would suffice, but you're
probably right it wouldn't...
def _write_data(filename, data, flags):
fileobject = open(filename, flags)
try: fileobject.write(data)
finally: fileobject.close()

def write_data(filename, data, flags="wb"):
_write_data(filename, data, flags)

def write_text(filename, text, flags="w"):
_write_data(filename, data, flags)

plus the corresponding read_data() and read_text() functions.
Hm, add an encoding for unicode, maybe...
Cookbook recipe, or standard lib?


I'm tempted to add convenience to the write_data wrapper by accepting
some non-str type for data, but that might be going overboard...
Alex
Jul 18 '05 #8
[snip..]
I'd suggest to expand this a bit, and make it working correctly on
windows too, where binary files must be opened with the 'b' flag:

def _write_data(filename, data, flags):
fileobject = open(filename, flags)
try: fileobject.write(data)
finally: fileobject.close()

def write_data(filename, data, flags="wb"):
_write_data(filename, data, flags)

def write_text(filename, text, flags="w"):
_write_data(filename, data, flags)

plus the corresponding read_data() and read_text() functions.
Hm, add an encoding for unicode, maybe...
Cookbook recipe, or standard lib?

Thomas

Hmm...I have a set of functions as a module - readfile, writefile,
readlines, writelines. My guess is that *everyone* has a similar
module they've written themselves. It can be a PITA cutting and
pasting the functions for a single line job sometimes. It would be a
useful addition to the standard lib.

Regards,

Fuzzy
Jul 18 '05 #9

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

18 posts views Thread by JKop | last post: by
3 posts views Thread by pooja | last post: by
11 posts views Thread by ambika | last post: by
22 posts views Thread by Daniel Billingsley | last post: by
18 posts views Thread by UJ | last post: by
reply views Thread by wal | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.