【发布时间】:2010-02-09 13:22:54
【问题描述】:
我正在使用 python 函数获取几个文件的 MD5:
filehash = hashlib.md5(file)
print "FILE HASH: " + filehash.hexdigest()
虽然当我去终端做一个
md5 file
我得到的结果与我的 python 脚本输出的结果不同(它们不匹配)。有人知道为什么吗?
【问题讨论】:
我正在使用 python 函数获取几个文件的 MD5:
filehash = hashlib.md5(file)
print "FILE HASH: " + filehash.hexdigest()
虽然当我去终端做一个
md5 file
我得到的结果与我的 python 脚本输出的结果不同(它们不匹配)。有人知道为什么吗?
【问题讨论】:
hashlib.md5() 获取文件的内容而不是文件名。
见http://docs.python.org/library/hashlib.html
您需要打开文件,并在散列之前读取其内容。
f = open(filename,'rb')
m = hashlib.md5()
while True:
## Don't read the entire file at once...
data = f.read(10240)
if len(data) == 0:
break
m.update(data)
print m.hexdigest()
【讨论】:
f.read(10240) 中读取的 10240 字节有什么神奇之处吗?对最佳尺寸有任何想法吗?
m.update(data) 不适用于不是 128 倍数的卡盘。我的磁盘有 4096 字节扇区,因此使用该扇区大小的倍数可能是有意义的128. 我使用f.read(128*4096) 或 512k 作为缓冲区。工作得快一点。我尝试了比这更小的,比如只有 128*5、128*10,但速度要慢得多。我会说您使用的 10K 大小(128*80 btw)是可能的最佳速度与大小权衡。对我来说,更大的速度大约快 5% 或 10%。
$ md5 test.py
MD5 (test.py) = 04523172fa400cb2d45652d818103ac3
$ python
Python 2.6.1 (r261:67515, Jul 7 2009, 23:51:51)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import hashlib
>>> s = open('test.py','rb').read()
>>> hashlib.md5(s).hexdigest()
'04523172fa400cb2d45652d818103ac3'
【讨论】:
试试这个
filehash = hashlib.md5(open('filename','rb').read())
print "FILE HASH: " + filehash.hexdigest()
【讨论】:
file 是什么?它应该等于open(filename, 'rb').read()。是吗?
【讨论】: