1

I have written these lines in a file

AA
BB
CC

With the following python code

f = open("foo.txt",'r')
for line in f:
    print (line)

I see that there is a newline between each line that is reads from

AA

BB

CC

# terminal prompt

How can I remove those new lines?

mahmood
  • 23,197
  • 49
  • 147
  • 242

2 Answers2

2

You can instead call print as

print(line, end='')

to prevent print from adding an newline on top of the ones read from the file.

kopecs
  • 1,545
  • 10
  • 20
2

This is because each line includes newline character(s), and print prints a newline character after everything else, for a total of up-to 2 newlines (the last line might have only 1).

You could strip the newline characters from the line.

f = open("foo.txt",'r')
for line in f:
    print(line.rstrip('\r\n'))
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171