ProgrammingOverflow
ProgrammingOverflow

Reputation: 11

Python program prints one blank line after reading a text file

I'm doing some simple python exercises in which the target is to simply read a text file and then print it. But my program prints one extra blank line.

Text file is model.txt, which has 3 text rows and 1 blank row, is displayed here

First row
Second row
This is the third row

My program is

file1=open("model.txt","r")
while True:
    row=file1.readline()
    print(row[:-1])
    if row=="":
        break
file1.close()

Now the wanted print result is:

First row
Second row
This is the third row

But instead there is one extra blank line after the print:

First row
Second row
This is the third row

There is a way to remove that one blank line but I haven't been able to figure it out.

Upvotes: 1

Views: 1640

Answers (3)

Luuk
Luuk

Reputation: 14929

file = open("model.txt", "r") 
for line in file: 
   print(line, end='')

Because the newline is read, it can also print printed with line, no need for line[:-1]

The 'end' option is left here as I need to read this page, filter out some python2 stuff, and then try to understand what that does do ;) How to print without newline or space?

Upvotes: 0

Its because your loop doesn't break soon enough. Read your file like this instead:

with open('model.txt', 'r') as file1:
  for line in file1.readlines():
      trimmed_line = line.rstrip()
      if trimmed_line: # Don't print blank lines
          print(trimmed_line)

The with statement will handle automatically closing the file and the rstrip() removes the \n and spaces at the end of the sentence.

Upvotes: 2

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

By default print() adds LF to each line printed, so if your print(row[:-1]) is empty (row[:-1] is empty string) then you still will get that behavior. The workaround would be to replace

print(row[:-1])

with

val = row[:-1]
if val: 
    print(val)

so empty value is not printed.

Upvotes: 1

Related Questions