This issue is due to incompatibility between python 2.x cPickle and python 3.x pickle.
(x, y) = pickle.load(ofname, encoding='latin1)
Below are two different applications that are successful, serializing and deserializing data:
- The following class belongs to the class that defines the binary data format:
# user.py
class User:
def __init__(self,name,age):
self.name = name
self.age = age
def show(self):
print(f'Name: {self.name}\nAge: {self.age}\n')
- The following standalone application writes data to the binary file:
# picker.py
import pickle, user
with open('user.dat','wb') as f:
n = int(input("Enter number of users: "))
for i in range(n):
name = input("Enter Name: ")
age = input("Enter Age: ")
ob = user.User(name,age)
pickle.dump(ob, f)
print('Done')
- The following standalone application reads data from the binary file:
# unpicker.py
import pickle, user
with open('user.dat','rb') as f:
while True:
try:
# Note that the encoding argument is used in the picker.load() method.
obj = pickle.load(f, encoding='latin1')
obj.show()
except EOFError:
print('Done')
break