首页 > 解决方案 > 从 2 TypeError 更新到 python3: can only concatenate str (not "bytes") to str

问题描述

当尝试将模块从 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

解决方案


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

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

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

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


推荐阅读