Can read() and readline() be used together?
<p>Is it possible to use both read() and readline() on one text file in python?</p>

<p>When I did that, it will only do the first reading function.</p>

<pre><code>file = open(name, "r")
inside = file.readline()
inside2 = file.read()

print(name)
print(inside)
print(inside2)
</code></pre>

<p>The result shows only the <code>inside</code> variable, not <code>inside2</code>.</p>

<p>Reading a file is like reading a book.  When you say <code>.read()</code>, it reads through the book until the end.  If you say <code>.read()</code> again, well you forgot one step.  You can't read it again unless you flip back the pages until you're at the beginning.  If you say <code>.readline()</code>, we can call that a page.  It tells you the contents of the page and then turns the page.  Now, saying <code>.read()</code> starts there and reads to the end.  That first page isn't included.  If you want to start at the beginning, you need to turn back the page.  The way to do that is with the <code>.seek()</code> method.  It is given a single argument: a character position to seek to:</p>

<pre><code>with open(name, 'r') as file:
    inside = file.readline()
    file.seek(0)
    inside2 = file.read()
</code></pre>

<p>There is also another way to read information from the file.  It is used under the hood when you use a <code>for</code> loop:</p>

<pre><code>with open(name) as file:
    for line in file:
        ...
</code></pre>

<p>That way is <code>next(file)</code>, which gives you the next line.  This way is a little special, though.  If <code>file.readline()</code> or <code>file.read()</code> comes after <code>next(file)</code>, you will get an error that mixing iteration and read methods would lose data.  (Credits to Sven Marnach for pointing this out.)</p>

python