Faber
Faber

Reputation: 45

what is a for loop doing on file objects?

I have a question related to Python for loops and files.

In this 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 <open file 'MVL_ref.txt', mode 'r' at 0x0267D230>

print f.read() # same output of the for-cycle
print f.readline() # same output of the for-cycle

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:

for line in f.read():
    print line 

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.

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".

Thank you for all the explanations that will come.

Upvotes: 1

Views: 1262

Answers (1)

m.antkowicz
m.antkowicz

Reputation: 13581

Since file object in Python is iterable you can iterate over it to get lines of file one-by-one.

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

l = ["line1", "line2"]
print l 

but you will see entity description

<open file 'path_to_the_file', mode 'r' at 0x0245D020>

Upvotes: 2

Related Questions