what is a for loop doing on file objects?
<p>I have a question related to Python for loops and files. </p>

<p>In this code: </p>

<pre><code>file = raw_input("input a text file ")

f = open(file) #  creates a file object of file

for line in f:
    # prints each line in the file
    print line 



print f

# prints &lt;open file 'MVL_ref.txt', mode 'r' at 0x0267D230&gt;

print f.read() # same output of the for-cycle
print f.readline() # same output of the for-cycle
</code></pre>

<p>The for-loop is printing each line that is present in my text 
file. However, if I print the file object I get something totally different.
This puzzles me because I would expect that I had to use something like:</p>

<pre><code>for line in f.read():
    print line 
</code></pre>

<p>but of course this is not the case.
If I use the read or readline methods without a for-loop I get the same output of the for-loop. </p>

<p>Is the for-loop doing some magic like calling read() or readline() by default on the file object? I am learning how to code with python but I fell I don't really understand much of what the code is doing "behind my back".   </p>

<p>Thank you for all the explanations that will come.</p>

<p>Since file object in Python is <a href="https://docs.python.org/2/glossary.html#term-iterable" rel="nofollow">iterable</a> you can iterate over it to get lines of file one-by-one. </p>

<p>However File is not a collection but object - you won't see all lines by printing this like when outputting collection</p>

<pre><code>l = ["line1", "line2"]
print l 
</code></pre>

<p>but you will see entity description</p>

<pre><code>&lt;open file 'path_to_the_file', mode 'r' at 0x0245D020&gt;
</code></pre>

python python-2.7