UtterlyRocked
UtterlyRocked

Reputation: 31

'.readline()' won't print when put into 'while' statement's condition

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!

Upvotes: 2

Views: 445

Answers (1)

pho
pho

Reputation: 25490

You seem to be running this in a REPL such as IDLE or a notebook, instead of a regular python interpreter.

A REPL prints the values of expressions, which is why you see the output of f.tell(). while f.readline() != '' is a statement, not an expression, so the REPL won't print its value (because a statement doesn't have a value). What is the difference between an expression and a statement in Python?

Note that when you run this in a regular interpreter, such as by doing python myfile.py in your command line, you won't see the output of f.tell() either.

If you want something printed, print() it.

f = open("./foo.txt", "r")

print(f.tell())

while line := f.readline():
    print(line)

print(f.tell())

Here, I used the walrus operatorPython3.8+ to assign the return from f.readline() to the variable line and before printing it inside the loop. Also, since empty strings are falsy anyway, you don't need to compare it against an empty string.

Upvotes: 1

Related Questions