Zipped and pickle

Thomas Lehmann Iris-und-Thomas-Lehmann at T-Online.de
Thu Sep 17 01:57:49 EDT 2009


> Briefly:
>
> 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()



More information about the Python-list mailing list