Newbie requires help me on how to use the ZipFile module please.
David Fraser
davidf at sjsoft.com
Thu Nov 25 03:30:59 EST 2004
Ian Cook wrote:
> Hi,
> Can someone PLEASE shed some light on using the ZipFile module
> correctly.
> I'm new to python so please excuse me if this is a 'dumb' question.
>
> If I use mode='a' then what happens is the zip file just gets bigger
> and bigger as the SAME file is appended to the zipfile.
>
> If I use mode='w' then what happens is the zip file is erased before
> adding files to it. Therefore I lose the files that were in the
> original file zipfile.
>
> What I want is to use the ZipFile module to UPDATE an existing zip
> file, rather than append, or create a new zip file. The zip file then
> contains my original files and any updated files.
>
> Does anyone know how this can be done with the Zipfile module?
>
> This is a snippet of the code I have now..
>
> try:
> zf = zipfile.ZipFile(zfname,mode='a')
> except:
> zf = zipfile.ZipFile(zfname,mode='w')
>
> for name in cutflist:
> fp = os.path.join(root,name)
> print "adding ",fp,"...",
> compresstype = zipfile.ZIP_DEFLATED
> if zipfile.is_zipfile(fp):
> compresstype = zipfile.ZIP_STORED
> zf.write(fp,compress_type=compresstype)
> print 'done.'
>
>
>
> Thanks in advance.
>
> Ian Cook
Curious, I posted a reply to the similar question you posted a week or
two ago, but it doesn't show up in google groups... even though I got it
from my nntp server...
So I'll post it again and Cc you :-)
Instead of attaching the file, you can get it here:
http://cvs.sourceforge.net/viewcvs.py/*checkout*/translate/src/translate/misc/zipfileext.py?rev=1.3
>
> This is the module translate.misc.zipfileext from translate.sourceforge.net
> I use it to do updating of zip files (it adds some stuff on top of the normal zipfile class that I should really submit as a patch :-) )
> Can't recall all the details but I think even so its a bit hairy.
> For an example you could look at http://cvs.sourceforge.net/viewcvs.py/translate/src/translate/storage/xpi.py?rev=1.33&view=auto
>
> The key method being this:
> def overwritestr(self, zinfo_or_arcname, bytes):
> """writes the string into the archive, overwriting the file if it exists..."""
> if isinstance(zinfo_or_arcname, zipfile.ZipInfo):
> filename = zinfo_or_arcname.filename
> else:
> filename = zinfo_or_arcname
> if filename in self.NameToInfo:
> self.delete(filename)
> self.writestr(zinfo_or_arcname, bytes)
> self.writeendrec()
>
> Basically you need to delete existing files before you write to them if you want to replace them.
>
> (This became more tricky) tricky as I was modifying zip files within zip files and trying to get them to store correctly, I ended up cloning the zip file objects, catching close events etc)
> Anyway maybe you can find something there that will help you.
>
> David
More information about the Python-list
mailing list