<p>尽管你大声否认,你可以在这里使用<code>mmap</code>。在</p>
<p>如果您看一下<a href="http://docs.python.org/2/library/mmap.html#mmap.mmap" rel="nofollow">^{<cd1>} constructor in the docs</a>,它接受<code>offset</code>和{<cd4>}的参数。在大多数平台上,两者都必须是<code>PAGESIZE</code>的倍数或类似值,但这并不难。在</p>
<p>所以:</p>
<pre><code>try:
PAGESIZE = mmap.PAGESIZE
except NameError:
PAGESIZE = mmap.ALLOCATION_GRANULARITY
def overwrite(fileobj, start, end, newbytes):
startoffset, startremainder = divmod(start, PAGESIZE)
offset = startoffset * PAGESIZE
endoffset, endremainder = divmod(end, PAGESIZE)
length = (endoffset + 1) * PAGESIZE - offset
map = mmap.mmap(fileobj.fileno(), offset=offset, length=length,
access=mmap.ACCESS_WRITE)
map[startremainder:startremainder+end-start] = newbytes
</code></pre>
<p>这样做的好处是,如果<code>len(newbytes) != end - start</code>你会从<code>mmap</code>得到一个很好的异常,而不是像你所想的那样或多或少地覆盖文件,使文件损坏。在</p>
<p>但是使用<code>seek</code>可能更简单,就像Martijn Pieters的回答一样。以下是与<code>seek</code>相同的函数:</p>
^{pr2}$
<p>不过,值得知道<code>mmap</code>可以做什么,这样您就不会在将来的有用案例中忽略它。在</p>
<p>(另外,对于某些版本的Python,在某些平台上,可能会有太大而无法<code>seek</code>的文件。例如,linux <code>/proc/*/map</code>是一个大小为<code>1<<64</code>的稀疏文件,但是在某些发行版上,Python找不到<code>fseeko</code>,因此不能搜索到比<code>1<<63</code>更远的地方。因此,了解其他方法来做这件事-<code>os.lseek</code>,<code>mmap</code>等等-也许有一天能帮助你解决一个问题。)</p>