1

I read file and print lines using python 2.7.8. But python always prints some extra empty lines.

I use the function:

def reverse(x):
    linelist = open(x, 'r').readlines()
    linelist.reverse()
    for line in linelist:
        print line

The content in my file is:

She sells seashells on the seashore;

The shells that she sells are seashells I`m sure.

So if she sells seashells on the seashore,

I`m sure that the shells are seashore shells.

But in the output, the last two print lines have extra empty lines:

I`m sure that the shells are seashore shells.

So if she sells seashells on the seashore,


The shells that she sells are seashells I`m sure.


She sells seashells on the seashore;


2 Answers 2

2

readlines keeps the newline \n character of every line. You should use rstrip before printing the line:

for line in linelist:
    print line.rstrip('\n')
Sign up to request clarification or add additional context in comments.

2 Comments

Why the first two lines can print exactly?
Sorry I did not understand you comment.
0

readlines gives an extra line by default. So, try adding a comma(,) after line

for line in linelist: print line,

1 Comment

Why the first two lines can print exactly?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.