Using pickle.dump - TypeError: must be str, not bytes Using pickle.dump - TypeError: must be str, not bytes python python

Using pickle.dump - TypeError: must be str, not bytes


The output file needs to be opened in binary mode:

f = open('varstor.txt','w')

needs to be:

f = open('varstor.txt','wb')


Just had same issue. In Python 3, Binary modes 'wb', 'rb' must be specified whereas in Python 2x, they are not needed. When you follow tutorials that are based on Python 2x, that's why you are here.

import pickleclass MyUser(object):    def __init__(self,name):        self.name = nameuser = MyUser('Peter')print("Before serialization: ")print(user.name)print("------------")serialized = pickle.dumps(user)filename = 'serialized.native'with open(filename,'wb') as file_object:    file_object.write(serialized)with open(filename,'rb') as file_object:    raw_data = file_object.read()deserialized = pickle.loads(raw_data)print("Loading from serialized file: ")user2 = deserializedprint(user2.name)print("------------")