wingerse
wingerse

Reputation: 3796

Readline() in a loop is not working in python

I have a file called file with this text:

Hello
I am not a bot
I am a human
Do you believe me?
I know you won't
Yes I am a bot
Yes you thought it right

This code prints out all the lines of the text:

with open(file) as f:
    for i in f:
        print(i,end="")

But this code does not, and I don't understand why.

with open(file) as f:
    for i in f:
        print(f.readline(),end="")

This prints out:

I am not a bot
Do you believe me?
Yes I am a bot

What I understand is as the loop goes over the lines in the file, it will read that line and return that as a string which is then printed. If I replace the for loop with for i in range(9), it works.

Upvotes: 0

Views: 1888

Answers (1)

Elisha
Elisha

Reputation: 4951

the for loop over the file object calls implicitly to readline (or equivalent) so what is happend is that in each loop you call readline twice, and this is why you get every second line

Upvotes: 5

Related Questions