<p>作为参考,这里有一个更简洁的版本:</p>
<pre><code>def sha1OfFile(filepath):
import hashlib
with open(filepath, 'rb') as f:
return hashlib.sha1(f.read()).hexdigest()
</code></pre>
<p>再想一想:虽然我从未见过,但我认为有可能<code>f.read()</code>返回的文件比完整文件少,或者有可能返回许多GB的文件,使f.read()耗尽内存。对于每个人的启迪,让我们考虑一下如何解决这个问题:第一个解决方法是:</p>
<pre><code>def sha1OfFile(filepath):
import hashlib
sha = hashlib.sha1()
with open(filepath, 'rb') as f:
for line in f:
sha.update(line)
return sha.hexdigest()
</code></pre>
<p>然而,根本不能保证<code>'\n'</code>出现在文件中,因此<code>for</code>循环将给我们以<code>'\n'</code>结尾的文件块这一事实可能会给我们带来与原来相同的问题。遗憾的是,我没有看到任何类似的python方法来迭代尽可能大的文件块,我认为,这意味着我们陷入了<code>while True: ... break</code>循环和块大小的幻数:</p>
<pre><code>def sha1OfFile(filepath):
import hashlib
sha = hashlib.sha1()
with open(filepath, 'rb') as f:
while True:
block = f.read(2**10) # Magic number: one-megabyte blocks.
if not block: break
sha.update(block)
return sha.hexdigest()
</code></pre>
<p>当然,谁说我们可以存储1兆字节的字符串。我们也许可以,但是如果我们在一台微型嵌入式计算机上呢?</p>
<p>我希望我能想出一个更干净的方法,保证不会在巨大的文件上耗尽内存,而且没有神奇的数字,而且性能和最初的简单Pythonic解决方案一样好。</p>