I am new to python and came across a object deserialisation issue (unpickling) while testing a program on jupyter lab.
I am trying to serialize and deserialize object of Employee class as below.
- Definition of Employee class:
class Employee:
def __init__(self, id, name, salary):
self.id = id
self.name = name
self.salary = salary
def display(self):
print('{:5d} -- {:20s} -- {:10.2f}'.format(self.id, self.name, self.salary))
- Code to pickle Employee Object:
import pickle
file = open('employee-data.csv', 'wb')
n = int(input('How many employees ?'))
for i in range(n):
id = int(input('Enter the Employee id:'))
name = input('Enter the Employee name:')
salary = float(input('Enter the Employee salary:'))
ob = Employee(id, name, salary)
pickle.dump(ob,file)
file.close()
- Code to unpickle Employee Object:
import pickle
file2 = open('employee-data.csv', 'rb')
print('Employee Details ....')
while True:
try:
obj = pickle.load(file2)
obj.display()
except EOFError:
print('End of File Reached ...')
break
file2.close()
Error:
> ---------
UnpicklingError Traceback (most recent call
> last) Cell In[5], line 9
> 7 while True:
> 8 try:
> ----> 9 obj = pickle.load(file2)
> 10 obj.display()
> 11 except EOFError:
>
> UnpicklingError: invalid load key, '\xef'.
Following snapshot shows that the code to serialize the object has run successfully. And the file was created.
What can be the problem here ? Any suggestions/feedbacks appreciated.

Employeeinstances that make the code fail, the creation of which is preferably hard-coded and not viainput())? Maybe also add OS and Python version info. As a side-note: I would not call the file*.csv, sincepickledoes not produce CSV files (i.e. comma-separated text files).pickle.dump()orfile.close()was not completed, so a corrupted file was written. I guess you now wrote a completely new file rather than just changing the suffix from.csvto.pkl? To be more error-proof, I agree with Surya R's comment: use awith open(...) as file:context for reading and writing, rather than callingclose()explicitly. See example here. I won't add an answer, since I don't think I provided a solution.