<p>简单的解决方案是<a href="https://docs.python.org/2/library/binascii.html" rel="nofollow noreferrer">^{<cd1>}</a>:</p>
<pre><code>import binascii
# Open in binary mode (so you don't read two byte line endings on Windows as one byte)
# and use with statement (always do this to avoid leaked file descriptors, unflushed files)
with open('data.geno', 'rb') as f:
# Slurp the whole file and efficiently convert it to hex all at once
hexdata = binascii.hexlify(f.read())
</code></pre>
<p>这只会得到十六进制值的<code>str</code>,但它的速度比您尝试的要快得多。如果您真的需要一组长度为每个字节2个十六进制字符串,您可以很容易地转换结果:</p>
<pre><code>hexlist = map(''.join, zip(hexdata[::2], hexdata[1::2]))
</code></pre>
<p>它将生成与每个字节的十六进制编码相对应的len 2<code>str</code>s的列表。为了避免<code>hexdata</code>的临时副本,可以使用类似但稍不直观的方法,通过使用同一个迭代器两次使用<code>zip</code>来避免切片:</p>
<pre><code>hexlist = map(''.join, zip(*[iter(hexdata)]*2))
</code></pre>
<p><strong>更新:</strong></p>
<p>对于Python 3.5及更高版本的用户,<a href="https://docs.python.org/3/library/stdtypes.html#bytes.hex" rel="nofollow noreferrer">^{<cd6>} objects spawned a ^{<cd7>} method</a>,因此不需要模块将原始二进制数据转换为ASCII hex。顶部的代码块可以简化为:</p>
<pre><code>with open('data.geno', 'rb') as f:
hexdata = f.read().hex()
</code></pre>