ZIP files

Ivo Woltring Python at IvoNet.nl
Wed Nov 10 14:30:22 EST 2004


On 10 Nov 2004 08:05:28 -0800, oriana.falco at 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.



More information about the Python-list mailing list