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
  • 21,089
  • 43
  • 130
  • 209

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,218
  • 9
  • 17
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
  • 56,044
  • 17
  • 157
  • 163