file.readlines leaving blank lines

I read that it file.readlinesreads the entire file line by line and saves it in a list. If I have a file like so -

Sentence 1
Sentence 2
Sentence 3

and I use readlinesto print each sentence like this -

file = open("test.txt") 
for i in file.readlines():
    print i

Exit

Sentence 1

Sentence 2

Sentence 3

My question is: why do I get an extra line between each sentence and how can I get rid of it?

UPDATE

I found that using i.stripalso removes extra lines. Why is this happening? As far as I know, splitremoves spaces at the end and beginning of a line.

+4
source share
4 answers

file.readlines() . . print newlnie.; .

, str.rstrip:

print i.rstrip('\n')

sys.stdout.write

sys.stdout.write(i)

, file.readlines, . .

with open("test.txt") as f:
    for i in f:
        print i.rstrip('\n')
        ...

UPDATE

Python 3, print , print(i, end='').

Python 2 : from __future__ import print_function

UPDATE

, Newlines .

>> ' \r\n\t\v'.isspace()
True
+7
file.readlines()

( file.readline()) .

Do

print i.replace('\n', '')

.

, , , , . I/O .

+1

A new line will be highlighted below.

i = i.rstrip("\n") #strips newline

Hope this helps.

+1
source

This worked for me with Python 3. I found the rstrip () function really useful in these situations

for i in readtext:
    print(i.rstrip())
0
source

All Articles