Discussion:
Zipped and pickle
(too old to reply)
Thomas Lehmann
2009-09-16 11:40:10 UTC
Permalink
How do I implement best to use pickle that way that the file is zipped?
Carl Banks
2009-09-16 19:54:37 UTC
Permalink
Post by Thomas Lehmann
How do I implement best to use pickle that way that the file is zipped?
Briefly:

s = cPickle.dumps(obj)
z = zipfile.Zipfile("filename.zip","w",zipfile.ZIP_DEFLATED)
z.writestr("arcname.pkl",s)


Carl Banks
Thomas Lehmann
2009-09-17 05:57:49 UTC
Permalink
Post by Carl Banks
s = cPickle.dumps(obj)
z = zipfile.Zipfile("filename.zip","w",zipfile.ZIP_DEFLATED)
z.writestr("arcname.pkl",s)
Thank you very much. I have not been aware that pickle can also do the
job without a file!
Here's the complete scenario for writing and reading the data...

APPENDIX:

import pickle
import zipfile

def test1():
print("test1...")

# create data
data = {}
data["first name" ] = "Thomas"
data["second name"] = "Lehmann"
data["hobbies" ] = ["programming python"]
print (data)

# pickle data
pickleString = pickle.dumps(data)
# save string to zip under a name
file = zipfile.ZipFile("ZippedPickle.zip", "w",
zipfile.ZIP_DEFLATED)
file.writestr("some data", pickleString)
file.close()

def test2():
print("test2...")
file = zipfile.ZipFile("ZippedPickle.zip", "r",
zipfile.ZIP_DEFLATED)
# reading zipped string store under a name
pickleString = file.read("some data")
# unpickle string to original data
data = pickle.loads(pickleString)
print (data)
file.close()

if __name__ == "__main__":
test1()
test2()

Loading...