如何解决 Python 错误 UnicodeDecodeError: ‘utf-8’ codec can’t decode invalid start byte

当我们在解码字节对象时指定不正确的编码时,会出现 Python “UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xff in position 0: invalid start byte”。 要解决错误,需要指定正确的编码,例如 utf-16 或以二进制模式(rb 或 wb)打开文件。

如何解决 Python 错误 UnicodeDecodeError: 'utf-8' codec can't decode invalid start byte

my_bytes = 'hello ÿ'.encode('utf-16')

# ⛔️ UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
my_str = my_bytes.decode('utf-8')

编码是将字符串转换为字节对象的过程,解码是将字节对象转换为字符串的过程。

解码字节对象时,我们必须使用与将字符串编码为字节对象相同的编码。

在示例中,我们可以将编码设置为 utf-16

my_bytes = 'hello ÿ'.encode('utf-16')

my_str = my_bytes.decode('utf-16')
print(my_str)  # ?️ "hello ÿ"

如果在打开文件时遇到错误,我们可以在不解码的情况下以二进制模式打开文件。

with open('example.txt', 'rb') as f:
    data = f.read()
    print(data)

我们以二进制模式(使用 rb 模式)打开文件,因此行列表包含字节对象。

以二进制模式打开文件时不应指定编码。

  • 如果我们需要将文件上传到远程服务器并且不需要对其进行解码,则可以使用此方法。
  • 如果需要与文件交互,可以将 errors 关键字参数设置为 ignore 以忽略无法解码的字符。

请注意,忽略无法解码的字符可能会导致数据丢失。

# ?️ 将 errors 设置为 ignore
with open('example.txt', 'r', encoding='utf-16', errors='ignore') as f:
    lines = f.readlines()

    print(lines)

使用 errors 设置为 ignore 的错误编码打开文件不会引发 UnicodeDecodeError

编码是将字符串转换为字节对象的过程,解码是将字节对象转换为字符串的过程。

解码字节对象时,我们必须使用与将字符串编码为字节对象相同的编码。

这是一个示例,它显示了如何使用与用于解码字节对象的编码不同的编码将字符串编码为字节导致错误。

my_text = 'hello ÿ'

my_binary_data = my_text.encode('utf-16')

# ⛔️ UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
my_text_again = my_binary_data.decode('utf-8')

我们可以通过使用 utf-16 编码来解码字节对象来解决这个错误。

my_text = 'hello ÿ'

my_binary_data = my_text.encode('utf-16')

my_text_again = my_binary_data.decode('utf-16')

print(my_text_again)  # ?️ "hello ÿ"