【发布时间】:2013-10-13 05:01:34
【问题描述】:
在 Python 2 中,只需运行即可散列字符串:
someText = "a"
hashlib.sha256(someText).hexdigest()
但在 Python 3 中,需要对其进行编码:
someText = "a".encode("ascii")
hashlib.sha256(someText).hexdigest()
但是当我用文件尝试这个时:
f = open(fin, "r")
sha = hashlib.sha256()
while True:
data = f.read(2 ** 20).encode("ascii")
if not data:
break
sha.update(data)
f.close()
我在很多文件上都得到了这个:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe1 in position 8: invalid continuation byte
我认为这是因为它是一个二进制文件,可能无法转换为 ASCII。
如何在没有这个问题的情况下对文件进行编码?
【问题讨论】:
-
尝试使用
open(fin, "rb")以二进制模式打开文件。 -
@BrenBarn 工作得很好,你应该这样回答。