python - 从 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()
解决方案
哈希函数适用于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
包含哈希摘要。
推荐阅读
- jquery - 烧瓶中使用的 javascript 和 jquery 文件在哪里?
- android - Android 11(R) 中的权限被拒绝问题
- javascript - web3.eth.accounts[0] 返回 undefined 并且 app.vote(1,{ from:web3.eth.accounts[0] }) 给出错误
- python - Python - Tabula - 字体中使用的 OpenType 布局表未在 PDFBox 中实现,将被忽略
- laravel - laravel中会话超时时如何触发事件处理程序?
- python - 用于获取没有特定标签的实例名称的 Lambda 脚本
- css - 一个组件中的样式优于另一个组件中的骑乘样式
- python - 在databricks pyspark中嵌套json到tsv
- flutter - Flutter 的 WebView - 如何允许在初始 URL 上发布数据?
- amazon-web-services - CodeDeploy 本地注册失败并在 Amazon Lightsail 上出现 AccessDeniedException