[Python] Python UnpicklingError: invalid load key, '\xef'

Discussão em 'Python' iniciado por Stack, Julho 31, 2025.

  1. Stack

    Stack Membro Participativo

    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.

    [​IMG]

    What can be the problem here ? Any suggestions/feedbacks appreciated.

    Continue reading...

Compartilhe esta Página