1

Can someone please help me why the below readline code is not giving expected result ?

f=open('Python_practice/Sample1.txt','r')
while f.readline() != '':
    print(f.readline(),end = '')
f.close()

Here - Am getting below o/p ( first and 3rd line is not coming ):
How are you ?
What about you ?

While when I am running below code, I am getting expected o/p.

f=open('Python_practice/Sample1.txt','r')
while True:
    data = f.readline()
    if data == '':
        break
    else:
        print(data,end = '')
f.close()

Hello!
How are you ?
I am fine, thanks.
What about you ?

f=open('Python_practice/Sample1.txt','r')
while f.readline() != '':
    print(f.readline(),end = '')
f.close()

I am expecting :
Hello!
How are you ?
I am fine, thanks.
What about you ?

Am getting below o/p ( first and 3rd line is not coming ):
How are you ?
What about you ?

Aditya
  • 11
  • 2
  • In the first example, you are calling `f.readline()` twice in every loop and discarding the result of the first while printing the second. This will have the effect of printing every second line. – Abion47 Apr 30 '23 at 04:04

1 Answers1

1

Like @Abion47 said, the reason it skips every second line is because you run f.readline() twice within the same iteration. In other words, you are saying to check if the current line is empty, and if true, read the next line and print it. Below I include a trace of what that loop is doing.

----iteration 1----

if "Hello!" is empty
print "How are you ?"

----iteration 2----

if "I am fine thanks" is empty
print "What about you ?"

---iteration 3----

if "" is empty
end

As a besides, reading text files like that does not seem to be the best approach. Consider using

with open('filename.txt') as fp:
    for line in fp:
        print(line)

Source

youngson
  • 85
  • 10