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

ID : 10124

viewed : 26

Tags : pythonpython-3.xpicklepython

Top 5 Answer for python - Using pickle.dump - TypeError: must be str, not bytes

vote vote

93

The output file needs to be opened in binary mode:

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

needs to be:

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

87

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 pickle  class MyUser(object):     def __init__(self,name):         self.name = name  user = 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 = deserialized print(user2.name) print("------------") 
vote vote

80

pickle uses a binary protocol, hence only accepts binary files. As the document said in the first sentence, "The pickle module implements binary protocols for serializing and de-serializing".

vote vote

60

vote vote

50

You can use arrow function ES2015/ES6 and just pass number to the parseInt. Default value for radix will be 10

[10, 20, 30].map(x => parseInt(x)) 

Or you can explicitly specify radix for better readability of your code.

[10, 20, 30].map(x => parseInt(x, 10)) 

In example above radix explicitly set to 10

Top 3 video Explaining python - Using pickle.dump - TypeError: must be str, not bytes

Related QUESTION?