confused about the readline() return in Python
<p>I am a beginner in python. However, I have some problems when I try to use the readline() method.</p>

<pre><code>f=raw_input("filename&gt; ")
a=open(f)
print a.read()
print a.readline()
print a.readline()
print a.readline()
</code></pre>

<p>and my txt file is </p>

<pre><code>aaaaaaaaa
bbbbbbbbb
ccccccccc
</code></pre>

<p>However, when I tried to run it on a Mac terminal, I got this:</p>

<pre><code>aaaaaaaaa
bbbbbbbbb
ccccccccc
</code></pre>

<p>It seems that  readline() is not working at all.
But when I disable print a.read(), the readline() gets back to work.</p>

<p>This confuses me a lot. Is there any solution where I can use read() and readline() at the same time? </p>

<p>The file object <code>a</code> remembers it's position in the file.</p>

<ul>
<li><code>a.read()</code> reads from the current position to end of the file (moving the position to the end of the file)</li>
<li><code>a.readline()</code> reads from the current position to the end of the line (moving the position to the next line)</li>
<li><code>a.seek(n)</code> moves to position n in the file (without returning anything)</li>
<li><code>a.tell()</code> returns the position in the file.</li>
</ul>

<p>So try putting the calls to readline first. You'll notice that now the read call won't return the whole file, just the remaining lines (maybe none), depending on how many times you called readline. And play around with seek and tell to confirm whats going on.</p>

<p>Details <a href="https://docs.python.org/2/library/stdtypes.html#bltin-file-objects" rel="nofollow">here</a>.</p>

python