I've been trying out file reading/writing instruments in Python and stumbled upon unintuitive behaviour of either readline()
method or while
statement. Assume the following few lines of code:
f = open("./foo.txt", "r") # file's not empty and contains several text strings
f.tell() # would return 0
while f.readline() != '': # as long as value returned is not an empty string...
pass
f.tell() # would now show the number of the last byte
What I expect:
The file would be opened in read-only mode. f.tell()
then would show us our current position within the file, which is 0
. Now in the while statement I expect that f.readline()
would be first executed so that with its returned value we could evaluate the expression. I also expect that, at the same time, the string extracted from the file would be printed to my output. This printing and evaluation will repeat until there are no more strings. The last f.tell()
will then tell us our current position within the file, it should now be the number of the last byte.
What happens:
File gets opened just as expected and the first f.tell()
shows me 0
. What happens next is that, apparently, f.readline()
gets executed and the expression gets evaluated correctly every iteration and loop finishes after it reaches file's end, but I never see any output besides returns from f.tell()
.
What do I want to know:
Why strings don't make it to the output? Could it be due to inner workings of Python's IO or is it how while
and, eventually, all compound statements handle some functions/methods?
Thank you!