1

When I run the code:

import pickle
ofname = open(r"ch05\dataset_small.pkl", 'rb')
(x, y) = pickle.load(ofname)

The error I get when running the code above is:

'ascii' codec can't decode byte 0xac in position 6: ordinal not in range(128)

How do I fix this error ?

1 Answers1

1

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:

  1. 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')
  1. 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')
  1. 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
Sercan
  • 4,739
  • 3
  • 17
  • 36