Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The quick answer:</p> <pre><code>f=open('filename') lines=f.readlines() print lines[25] print lines[29] </code></pre> <p>or:</p> <pre><code>lines=[25, 29] i=0 f=open('filename') for line in f: if i in lines: print i i+=1 </code></pre> <p>There is a more elegant solution for extracting many lines: <a href="http://docs.python.org/library/linecache.html" rel="noreferrer">linecache</a> (courtesy of <a href="https://stackoverflow.com/questions/620367/python-how-to-jump-to-a-particular-line-in-a-huge-text-file">"python: how to jump to a particular line in a huge text file?"</a>, a previous stackoverflow.com question).</p> <p>Quoting the python documentation linked above:</p> <pre><code>&gt;&gt;&gt; import linecache &gt;&gt;&gt; linecache.getline('/etc/passwd', 4) 'sys:x:3:3:sys:/dev:/bin/sh\n' </code></pre> <p>Change the <code>4</code> to your desired line number, and you're on. Note that 4 would bring the fifth line as the count is zero-based.</p> <p>If the file might be very large, and cause problems when read into memory, it might be a good idea to take <a href="https://stackoverflow.com/questions/2081836/reading-specific-lines-only-python/2081880#2081880">@Alok's advice and use enumerate()</a>.</p> <p><strong>To Conclude:</strong></p> <ul> <li>Use <code>fileobject.readlines()</code> or <code>for line in fileobject</code> as a quick solution for small files. </li> <li>Use <code>linecache</code> for a more elegant solution, which will be quite fast for reading many files, possible repeatedly.</li> <li>Take <a href="https://stackoverflow.com/questions/2081836/reading-specific-lines-only-python/2081880#2081880">@Alok's advice and use <code>enumerate()</code></a> for files which could be very large, and won't fit into memory. Note that using this method might slow because the file is read sequentially.</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload