我在解码必须从一台计算机发送到另一台计算机的字节字符串时遇到问题。文件为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''的大小。
在Python中,字节字符串用于原始二进制数据,而字符串用于文本数据。decode
尝试将其解码为utf-8,该格式对txt文件有效,但对pdf文件无效,因为它们可以包含随机字节。你不应该尝试获取字符串,因为字节字符串是为此目的而设计的。你可以使用来获取字节串的长度,就像普通的一样len(data)
。许多字符串操作也适用于字节字符串,例如串联和切片(data1 + data2
和data[1:3]
)。
附带说明一下,b''
打印时的原因仅仅是因为__str__
字节串的方法等效于repr
。它不在数据本身中。
当我使用len()时,它不将b''计入大小吗?编辑:不,它不将b''计入len,作为与我有同样问题的人的旁注。感谢您的回答@ Aplet123,它有所帮助。