Zip Files

I’ve been experimenting with pickling and zip files, and have most of it working with the exception of writing the actual zip file. I got it working once somehow, but it was constantly adding to the zipped archive instead of creating a new one, and now I’m back to square one.

This is my code:

import cPickle as P
import zipfile

tDict = {'1':100,'2':200,'3':Zip this stuff'}
file=open("C:\\Temp\\Test.txt",'w')
P.dump(tDict,file)
file.close()  #This part works fine

zip = open("C:\\Temp\\ZipTest.zip")
s=P.dumps(tDict) #This just creates a pickled byte object, not a file object
file = zipfile.ZipFile(zip,'w',zipfile,ZIP_DEFLATED)
file.writestr('zip',s) #This is where I'm having problems
file.close()

What am I supposed to use for the first writestr parameter? I’ve been referring to example code on the net, but I’m doing something wrong here.

Try this, I think you have to pass in a ZipInfo instance containing the name of the file inside the archive. I wonder if writestr won’t accept a string because it’s an older python version? (http://docs.python.org/library/string.html#string-formatting)? Also, zip is just a filename in a string.

[code]import cPickle as P
import zipfile

tDict = {‘1’:100,‘2’:200,‘3’:‘Zip this stuff’}
file=open(“C:\Temp\Test.txt”,‘w’)
P.dump(tDict,file)
file.close() #This part works fine

zip = “C:\Temp\ZipTest.zip”
zipcontent = zipfile.ZipInfo(“filename_in_zip.txt”)
s=P.dumps(tDict) #This just creates a pickled byte object, not a file object
file = zipfile.ZipFile(zip,‘w’,zipfile.ZIP_DEFLATED)
file.writestr(zipcontent,s)
file.close()[/code]

It looks like the write to the zip doesn’t include newlines. You may need to go line by line in the source file and stick a \r\n at the end before writing it out to the zip.

Dan

Thanks Dan! That works great.