0

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.

7
  • 2
    Why are you mixing iteration over the file object and readline calls? Iterating already reads the lines. Commented Sep 3, 2014 at 13:03
  • Yeah, but why does putting readline() there does not work? Commented Sep 3, 2014 at 13:06
  • 2
    It does work. You can see that it reads three of the lines in your file, just as you asked it to. (the fact that it doesn't read the lines already consumed by i, is not readline's fault) Commented Sep 3, 2014 at 13:07
  • Oh, I see. So readline() can't use it when i has the line consumed. Thanks :) Commented Sep 3, 2014 at 13:20
  • I often use the splitline() method that returns the lines in a list (i.e. data_lines = f.read().splitline() ) Commented Sep 3, 2014 at 13:57

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.