Why do I get different values for the
f.readline() statement in this bit of code? I entered it in the interactive mode of IDLE

>>> f=open('F:\\Documents and Settings\\folder1\\flder2\\t.txt','r')
>>> f.readlines()
['1\n', '2\n', '3\n', '4\n', '5\n', '6\n', '7\n', '8\n', '9\n', '10']
>>> f.readlines()
7 Years
Discussion Span
Last Post by mahela007

It's because when python reads a file, it has a position in the file and it reads from this position. After the call to open, the position is at the beginning of the file, but after readlines(), the position is at the end of the file. You could do this

>>> f = open(....)
>>> beginning = f.tell() # get the current position
>>> f.readlines() # read the whole file
>>> f.seek(beginning)  # go back to the beginning
>>> f.readlines() # should produce the same result as the first readlines()

in principle, seek accepts any value that was returned by a previous tell.


f.seek(0) will always return to the beginning of a file as well. If you print out the value of beginning in the code snippet above, you'll likely find that it is an integer == 0.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.