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()
[]

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.

thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.