ZIP files

Scott David Daniels Scott.Daniels at Acm.Org
Wed Nov 10 13:48:09 EST 2004


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
Scott.Daniels at Acm.Org



More information about the Python-list mailing list