Python reads in the file and stores it in the variable my_file
with the pointer at the start of the file or (0, 0)
. As you start doing readline
, python will read a line from the file and then "consume" it. In other words, the current pointer will now be waiting at the next line so when you call readline
, it will now get the next line.
Hope that helps
The equivalent of what you are expecting would be:
my_file = open("text.txt", "r")
print my_file.readline()
my_file.seek(0, 0)
print my_file.readline()
my_file.seek(0, 0)
print my_file.readline()
my_file.close()
In the above case, the seek(0, 0)
call resets the pointer's position to the start of the file after every readline
so in this case, you will end up printing the first line 3 times.