Question

      my_file = open("text.txt", "r")
      print my_file.readline()
      print my_file.readline()
      print my_file.readline()
      my_file.close()

I understand that/how this prints out the first three lines of the text file, but I'm not entirely sure why. Since I'm printing out my_file.readline(), why doesn't it print out the first line for all three times?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top