13

I have read that file.readlines reads the whole file line by line and stores it in a list. If I have a file like so -

Sentence 1
Sentence 2
Sentence 3

and I use readlines to print each sentence like so -

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

The output is

Sentence 1

Sentence 2

Sentence 3

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

UPDATE

I found that using i.strip also removes the extra lines. Why does this happen? As far as I know, split removes the white spaces at the end and beginning of a string.

busybear
  • 10,194
  • 1
  • 25
  • 42
MayankJain
  • 287
  • 1
  • 3
  • 9

5 Answers5

11

file.readlines() return list of strings. Each string contain trailing newlines. print statement prints the passed parameter with newlnie.; That's why you got extra lines.

To remove extra newline, use str.rstrip:

print i.rstrip('\n')

or use sys.stdout.write

sys.stdout.write(i)

BTW, don't use file.readlines unless you need all lines at once. Just iterate the file.

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

UPDATE

In Python 3, to prevent print prints trailing newline, you can use print(i, end='').

In Python 2, you can use same feature if you do : from __future__ import print_function

Answer to UPDATE

Tabs, Newlines are also considers as whitespaces.

>> ' \r\n\t\v'.isspace()
True
falsetru
  • 357,413
  • 63
  • 732
  • 636
1
file.readlines()

(and also file.readline()) includes the newlines.

Do

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

if you don't want them.

It may seem weird to include the newline at the end of the line, but this allows, for example, you to tell whether the last line has a newline character or not. That case in tricky in many languages' I/O.

Paul Draper
  • 78,542
  • 46
  • 206
  • 285
1

The below will strip the newline for you.

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

Hope this helps.

fscore
  • 2,567
  • 7
  • 40
  • 74
0

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

for i in readtext:
    print(i.rstrip())
Thinh Le
  • 603
  • 1
  • 7
  • 14
0
with open(txtname, 'r') as txtfile:
    lines = txtfile.readlines()
    lines = [j for j in lines if j != '\n']
with open(outname, 'w') as outfile:
    outfile.writelines(lines)
Burak
  • 2,251
  • 1
  • 16
  • 33