UnicodeDecodeError:'gbk'编解码器无法解码位置0非法多字节序列中的字节0x80

Hao*_*oyu 3 python encoding pickle

我使用python 3.4和win 7 64位系统.我运行了以下代码:

      6   """ load single batch of cifar """
      7   with open(filename, 'r') as f:
----> 8     datadict = pickle.load(f)
      9     X = datadict['data']
Run Code Online (Sandbox Code Playgroud)

错误的信息是 UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 0: illegal multibyte sequence

我将第7行更改为:

      6   """ load single batch of cifar """
      7   with open(filename, 'r'?encoding='utf-8') as f:
----> 8     datadict = pickle.load(f)
      9     X = datadict['data']
Run Code Online (Sandbox Code Playgroud)

错误的信息变成了UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte.

消息最终指向解码中的Python34\lib\codecs.py(self,input,final).

    311         # decode input (taking the buffer into account)
    312         data = self.buffer + input
--> 313         (result, consumed) = self._buffer_decode(data, self.errors, final)
    314         # keep undecoded input until the next call
    315         self.buffer = data[consumed:]
Run Code Online (Sandbox Code Playgroud)

我进一步将代码更改为:

      6 """ load single batch of cifar """ 
      7 with open(filename, 'rb') as f:
----> 8 datadict = pickle.load(f) 
      9 X = datadict['data'] 10 Y = datadict['labels']
Run Code Online (Sandbox Code Playgroud)

好吧,这次是UnicodeDecodeError: 'ascii' codec can't decode byte 0x8b in position 6: ordinal not in range(128).

有什么问题以及如何解决?

Mar*_*ers 10

Pickle文件是二进制数据文件,因此您始终必须'rb'在加载时使用该模式打开文件.这里不要尝试使用文本模式.

您正在尝试加载包含字符串数据的Python 2 pickle.您必须告诉pickle.load()如何将该数据转换为Python 3字符串,或将它们保留为字节.

默认是尝试将这些字符串解码为ASCII,并且解码失败.查看pickle.load()文档:

可选的关键字参数是fix_imports,encodingerrors,用于控制Python 2生成的pickle流的兼容性支持.如果fix_imports为true,则pickle将尝试将旧的Python 2名称映射到Python 3中使用的新名称.编码错误告诉pickle如何解码Python 2腌制的8位字符串实例; 这些默认分别为'ASCII'和'strict'.该编码可以是"字节"作为字节对象读取这些8位串的实例.

设置编码latin1可以直接导入数据:

with open(filename, 'rb') as f:
    datadict = pickle.load(f, encoding='latin1') 
Run Code Online (Sandbox Code Playgroud)

看来这numpy是导致问题的数组数据,因为集合中的所有字符串使用ASCII字符.

另一种方法是使用,encoding='bytes'但是所有的文件名和顶级字典键都是bytes对象,你必须解码这些或者用你的所有关键文字作为前缀b.


小智 9

如果您将使用 utf-8 打开文件,那么您需要编写:

open(file_name, 'r', encoding='UTF-8')
Run Code Online (Sandbox Code Playgroud)

如果您要使用 GBK 打开文件,那么您需要执行以下操作:

open(file_name, 'rb')
Run Code Online (Sandbox Code Playgroud)

希望能解决您的问题!