Warm tip: This article is reproduced from serverfault.com, please click

encoding-Python无法解码字节字符串

(encoding - Python unable to decode byte string)

发布于 2020-11-30 15:19:30

我在解码必须从一台计算机发送到另一台计算机的字节字符串时遇到问题。文件为PDF格式。我得到的错误是:

fileStrings[i] = fileStrings[i].decode()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xda in position 648: invalid continuation byte

关于如何删除b''标记的任何想法?我需要编译文件备份,但是在发送文件之前,我还需要知道其大小(以字节为单位),我想我可以通过解码每个字节字符串来知道它(适用于txt文件,但不适用于pdf文件。)

代码是:

    with open(inputne, "rb") as file:
        while 1:
            readBytes= file.read(dataMaxSize)
            fileStrings.append(readBytes)
            if not readBytes:
                break
            readBytes= ''
    
    filesize=0
    for i in range(0, len(fileStrings)):
        fileStrings[i] = fileStrings[i].decode()
        filesize += len(fileStrings[i])

编辑:对于有相同问题的任何人,参数len()将为你提供不带b''的大小。

Questioner
Dudo
Viewed
0
Aplet123 2020-11-30 23:22:20

在Python中,字节字符串用于原始二进制数据,而字符串用于文本数据。decode尝试将其解码为utf-8,该格式对txt文件有效,但对pdf文件无效,因为它们可以包含随机字节。不应该尝试获取字符串,因为字节字符串是为此目的设计的。你可以使用来获取字节串的长度,就像普通的一样len(data)许多字符串操作也适用于字节字符串,例如串联和切片(data1 + data2data[1:3])。

附带说明一下,b''打印时的原因仅仅是因为__str__字节串方法等效于repr它不在数据本身中。