对于Python2.7,下面的代码计算文件内容的mD5十六进制摘要。
(编辑:嗯,并不像答案所显示的那样,我只是认为是这样)。
import hashlib
def md5sum(filename):
f = open(filename, mode='rb')
d = hashlib.md5()
for buf in f.read(128):
d.update(buf)
return d.hexdigest()
现在,如果我使用python3运行该代码,它将引发TypeError异常:
d.update(buf)
TypeError: object supporting the buffer API required
我想我可以使用python2和python3来运行该代码,并将其更改为:
def md5sum(filename):
f = open(filename, mode='r')
d = hashlib.md5()
for buf in f.read(128):
d.update(buf.encode())
return d.hexdigest()
现在我仍然想知道为什么原始代码停止工作。似乎在使用binary模式修饰符打开文件时,它会返回整数,而不是以字节编码的字符串(我之所以这么说,是因为type(buf)返回int)。这种行为在什么地方得到了解释吗?
发布于 2011-10-20 08:20:33
在问完这个问题后,我最终将我的代码更改为下面的版本(我发现这个版本很容易理解)。但我可能会将其更改为Raymond Hetting unsing functools.partial建议的版本。
import hashlib
def chunks(filename, chunksize):
f = open(filename, mode='rb')
buf = "Let's go"
while len(buf):
buf = f.read(chunksize)
yield buf
def md5sum(filename):
d = hashlib.md5()
for buf in chunks(filename, 128):
d.update(buf)
return d.hexdigest()
https://stackoverflow.com/questions/7829499
复制相似问题