Error with .readlines()[n]
<p>I'm a beginner with Python.
I tried to solve the problem: "If we have a file containing &lt;1000 lines, how to print only the odd-numbered lines? ". That's my code:</p>

<pre><code>with open(r'C:\Users\Savina\Desktop\rosalind_ini5.txt')as f:
   n=1
   num_lines=sum(1 for line in f)
   while n&lt;num_lines:
         if n/2!=0:
                 a=f.readlines()[n]
                 print(a)
         break
    n=n+2
</code></pre>

<p>where <em>n</em> is a counter and <em>num_lines</em> calculates how many lines the file contains. 
But when  I try to execute the code, it says: </p>

<pre><code>"a=f.readlines()[n]
 IndexError: list index out of range"
</code></pre>

<p>Why it doesn't recognize <em>n</em> as a counter?</p>

<p>You have the call to <code>readlines</code> into a loop, but this is not its intended use,
because <code>readlines</code> ingests the whole of the file at once, returning you a LIST
of newline terminated strings.</p>

<p>You may want to save such a list and operate on it</p>

<pre><code>list_of_lines = open(filename).readlines() # no need for closing, python will do it for you
odd = 1
for line in list_of_lines:
    if odd : print(line, end='')
    odd = 1-odd
</code></pre>

<p>Two remarks:</p>

<ol>
<li><code>odd</code> is alternating between <code>1</code> (hence true when argument of an <code>if</code>) or <code>0</code> (hence false when argument of an <code>if</code>),</li>
<li>the optional argument <code>end=''</code> to the <code>print</code> function is required because each line in <code>list_of_lines</code> is terminated by a new line character, if you omit the optional argument the <code>print</code> function will output a SECOND new line character at the end of each line.</li>
</ol>

<p>Coming back to your code, you can fix its behavior using a</p>

<pre><code>f.seek(0)
</code></pre>

<p>before the loop to rewind the file to its beginning position and using the
<code>f.readline()</code> (look, it's NOT <code>readline**S**</code>) method inside the loop,
but rest assured that proceding like this is. let's say, a bit unconventional...</p>

<p>Eventually, it is possible to do everything you want with a one-liner</p>

<pre><code>print(''.join(open(filename).readlines()[::2]))
</code></pre>

<p>that uses the <a href="http://stackoverflow.com/q/509211/2749397">slice notation for list</a>s and the <a href="http://stackoverflow.com/q/12453580/2749397">string method <code>.join()</code></a></p>

python python-3.x while-loop