1

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.

3 Answers3

2

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.

1

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.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
0
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?

Luuk
  • 12,245
  • 5
  • 22
  • 33