<p>打开的文件不是UTF-8编码的,而系统的默认编码设置为UTF-8。</p>
<p>因为您正在计算SHA1散列,所以应该改为将数据读取为<em>binary</em>。<code>hashlib</code>函数要求传入字节:</p>
<pre><code>with open(filename, 'rb') as f:
return hashlib.sha1(f.read()).hexdigest() == sha1
</code></pre>
<p>注意在文件模式中添加了<code>b</code>。</p>
<p>请参见<a href="https://docs.python.org/3/library/functions.html#open" rel="noreferrer">^{<cd3>} documentation</a>:</p>
<blockquote>
<p><em>mode</em> is an optional string that specifies the mode in which the file is opened. It defaults to <code>'r'</code> which means open for reading in text mode. <em>[...]</em> In text mode, if <em>encoding</em> is not specified the encoding used is platform dependent: <code>locale.getpreferredencoding(False)</code> is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave <em>encoding</em> unspecified.)</p>
</blockquote>
<p>从<a href="https://docs.python.org/3/library/hashlib.html#hash-algorithms" rel="noreferrer">^{<cd1>} module documentation</a>:</p>
<blockquote>
<p>You can now feed this object with bytes-like objects (normally bytes) using the update() method.</p>
</blockquote>