Search code examples
pythonpython-3.xpickle

How to pickle and unpickle


import  pickle
variety = ["sweet", "box", "cat"]
shape = ["back","spear", "log"]
pickleFile = open("pickle.txt", 'w')
pickle.dump(variety, pickleFile)
pickle.dump(shape, pickleFile)
pickleFile.close()

pickleFile = open("pickle.txt", 'r')
test = pickle.load(pickleFile)
shape = pickle.load(pickleFile)

print ("variety : ", test, " shape : ", shape)
pickleFile.close()

when I run above code I get the following error

line 6, in <module>
pickle.dump(variety, pickleFile)
TypeError: must be str, not bytes

and i am not sure if unpickling in variable 'test' will be possible or not cause I had pickled in with variable 'variety'


Solution

  • According to help(pickle.dump),

    The file argument must have a write() method that accepts a single bytes argument. It can thus be a file object opened for binary writing, a io.BytesIO instance, or any other custom object that meets this interface.

    Looks like you have to open your file in binary mode. Don't forget to do the same for loading too.

    import  pickle
    variety = ["sweet", "box", "cat"]
    shape = ["back","spear", "log"]
    with open("file.pkl", 'wb') as picklefile:
        pickle.dump(variety, picklefile)
        pickle.dump(shape, picklefile)
    
    
    with open("file.pkl", 'rb') as picklefile:
        test = pickle.load(picklefile)
        shape = pickle.load(picklefile)
    
    print ("variety : ", test, " shape : ", shape)
    

    Result:

    variety :  ['sweet', 'box', 'cat']  shape :  ['back', 'spear', 'log']