Skip some bytes of a file and return content
<p>Given a list of byte ranges that have to be skipped:</p>

<pre><code>skip_ranges = [(1, 3), (5,7)]
</code></pre>

<p>and a binary file:</p>

<pre><code>f = open('test', 'rb')
</code></pre>

<p>What is the fastest way to return file contents without bytes 1-3 and 5-7 without modifying the original file?</p>

<p>Input (file contents):</p>

<pre><code>012345678
</code></pre>

<p>Output:</p>

<pre><code>048
</code></pre>

<p>Please note that this question is specifically about (possibly large) binary files, so a generator would be the best.</p>

<p>This approach should be relatively fast:</p>

<pre><code>ba = bytearray()
with open('test.dat','rb') as f:
    prev = -1
    for start, stop in skip_ranges:
        ba.extend(f.read(start - prev - 1))
        f.seek(stop + 1,0)
        prev = stop
    else:
        ba.extend(f.read())
</code></pre>

python python-2.7