简体   繁体   English

在 Python 3.8 中加载使用 Python 2.7 创建的 pickle 文件时出错

[英]Error loading pickle file created with Python 2.7 in Python 3.8

I have a pickle file which contains floating-point values.我有一个包含浮点值的泡菜文件。 This file was created with Python 2.7.这个文件是用 Python 2.7 创建的。 In Python 2.7 I used to load it like:在 Python 2.7 中,我曾经像这样加载它:

matrix_file = pickle.load(open('matrix.pickle', 'r'))

Now in Python 3.8 this code is giving error现在在 Python 3.8 中,这段代码给出了错误

TypeError: a bytes-like object is required, not 'str'

When I trid with 'rb' I got this error当我尝试使用 'rb' 时出现此错误

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 8: ordinal not in range(128)

So I tried another method所以我尝试了另一种方法

matrix_file = pickle.load(open('matrix.pickle', 'r', encoding='utf-8'))

Now I get a different error现在我得到一个不同的错误

TypeError: a bytes-like object is required, not 'str'

Update : When I try loading with joblib, I get this error更新:当我尝试使用 joblib 加载时,出现此错误

ValueError: You may be trying to read with python 3 a joblib pickle generated with python 2. This feature is not supported by joblib.

The file must be opened in binary mode and you need to provide an encoding for the pickle.load call.该文件必须以二进制模式打开,并且您需要为pickle.load调用提供encoding Typically, the encoding should either be "latin-1" (for pickles with numpy arrays, datetime , date and time objects, or when the strings were logically Latin-1), or "bytes" (to decode Python 2 str as bytes objects).通常, encoding应该是"latin-1" (对于带有numpy数组、 datetimedatetime对象的泡菜,或者当字符串逻辑上是 Latin-1 时)或"bytes" (将 Python 2 str解码为bytes对象)。 So the code should be something like:所以代码应该是这样的:

with open('matrix.pickle', 'rb') as f:
    matrix_file = pickle.load(f, encoding='latin-1')

This assumes it was originally containing numpy arrays;这假设它最初包含numpy数组; if not, "bytes" might be the more appropriate encoding.如果不是, "bytes"可能是更合适的编码。 I also used a with statement just for good form (and to ensure deterministic file closing on non-CPython interpreters).我还使用了一个with语句只是为了良好的形式(并确保在非 CPython 解释器上关闭确定性文件)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM