【问题标题】:Python unable to decode byte stringPython无法解码字节字符串
【发布时间】: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'' 的大小。

【问题讨论】:

  • "size in bytes" - 解码会将字节转换为字符,字符数与字节数不同。 是一个符号,但 3 个字节:b'\xe2\x88\x9e',或 UTF32 中的 8 个字节。

标签: python encoding decode


【解决方案1】:

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

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

【讨论】:

  • 当我使用 len() 时,它不会将 b' ' 计入大小吗?编辑:不,它不将 b' ' 计入 len,作为与我有相同问题的人的旁注。感谢您的回答@Aplet123,它有帮助。
猜你喜欢
  • 2012-05-22
  • 2012-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-29
  • 1970-01-01
  • 1970-01-01
  • 2010-10-14
相关资源
最近更新 更多