title: Python fastest access to nth line in huge file
body: <p>I have an ASCII table in a file from which I want to read a particular set of lines (e.g. lines 4003 to 4005).  The issue is that this file could be very very long (e.g. 100's of thousands to millions of lines), and I'd like to do this as quickly as possible.</p>
  <p><strong>a) Bad Solution</strong>:  Read in the entire file, and go to those lines,</p>
  <pre><code>f = open('filename')
  lines = f.readlines()[4003:4005]
  </code></pre>
  <p><strong>b) Better Solution</strong>: <code>enumerate</code> over each line so that it's not all in memory (<em>a la</em> <a href="https://stackoverflow.com/a/2081880/230468">https://stackoverflow.com/a/2081880/230468</a>)</p>
  <pre><code>f = open('filename')
  lines = []
  for i, line in enumerate(f):
      if i &gt;= 4003 and i &lt;= 4005: lines.append(line)
      if i &gt; 4005: break                                    # @Wooble
  </code></pre>
  <p><strong>c) Best Solution?</strong></p>
  <p>But b) still requires going through each line.</p>
  <p>Is there a better (in terms of speed/efficiency) method of accessing a particular line from a huge file?</p>
  <ul>
  <li>Should I use a <a href="http://docs.python.org/2/library/linecache.html?highlight=linecache#module-linecache" rel="nofollow noreferrer">linecache</a> even though I will only access the file once (typically)?</li>
  <li>Using a binary file instead, in which case it might be easier to skip-ahead, is an option --- but I'd much rather avoid it.</li>
  </ul>