【问题标题】:Updating to python3 from 2 TypeError: can only concatenate str (not "bytes") to str从 2 TypeError 更新到 python3: can only concatenate str (not "bytes") to str
【发布时间】:2019-04-14 05:09:15
【问题描述】:

在尝试将模块从 python 2 升级到使用 python 3 时,我在尝试对文件数据进行哈希处理时遇到类型错误,当我对数据进行编码时,我遇到了 TypeError “Unicode 对象必须在哈希之前进行编码”抛出 TypeError “只能将 str(不是“字节”)连接到 str”

    with open(realPath, "rb") as fn:
        while True:
            filedata = fn.read(self.piece_length)

            if len(filedata) == 0:
                break
            length += len(filedata)
            ##First error was here fixed with .decode()
            data += filedata.decode('utf-8')

            if len(data) >= self.piece_length:
                info_pieces += sha1(data[:self.piece_length]).digest()
                data = data[self.piece_length:]

            if check_md5:
                md5sum.update(filedata)
    if len(data) > 0:
        ##New error happens here
        info_pieces += sha1(data).digest()

【问题讨论】:

    标签: python


    【解决方案1】:

    哈希函数现在可以使用 bytes,而不是 str。所以你传递给sha1的对象应该是bytes.digest()的返回值也会是bytes

    所以你应该在传递给sha1()之前将字符串data编码为字节,例如:

    info_pieces += sha1(data[:self.piece_length].encode('utf-8')).digest()
    

    确保您已初始化变量,例如 data = ''info_pieces = b'',因为 data 是解码文本,info_pieces 包含哈希摘要。

    【讨论】:

      【解决方案2】:

      .digest() 返回一个“字节对象”,而不是字符串。你还需要decode()它,比如:

      info_pieces += sha1(data).digest().decode('utf-8')

      info_pieces += str(sha1(data).digest(), 'utf-8')

      【讨论】:

      • 我试过这样做,它只是吐出相同的“Unicode对象必须在散列之前编码”
      • 哦,抱歉,我在回答 when I encode the data it then throws a TypeError "can only concatenate str (not "bytes") to str" 部分。
      猜你喜欢
      • 2022-11-01
      • 2020-11-21
      • 2020-08-29
      • 1970-01-01
      • 2021-08-31
      • 2021-08-18
      • 2019-02-02
      • 2020-02-29
      • 2020-09-18
      相关资源
      最近更新 更多