2

I have a .pkl file which loads perfectly in my MAC OS but it wont load in a windows machine. I am using python 3 on anaconda. This is my code:

data=pickle.load(open("ydata1.pkl",'rb'))

Error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 2295: ordinal not in range(128)

So I tried this:

data=pickle.load(open("ydata1.pkl",'r'))

But I get an error saying : a bytes-like object is required, not 'str'

Can anyone please tell me where I am going wrong?

JustCurious
  • 780
  • 1
  • 10
  • 29

1 Answers1

0

Use open() with mode rb:

import pickle

with open('ydata1.pkl', 'rb') as p_f:
    data = pickle.load(p_f)

Taken from documentation: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

Also make sure you are not having Python 2 / Python 3 pickle compatibility issues: Pickle incompatibility of numpy arrays between Python 2 and 3

alexisdevarennes
  • 5,437
  • 4
  • 24
  • 38