thefourtheye
thefourtheye

Reputation: 239443

How to skip the extra newline while printing lines read from a file?

I am reading input for my python program from stdin (I have assigned a file object to stdin). The number of lines of input is not known beforehand. Sometimes the program might get 1 line, 100 lines or even no lines at all.

import sys
sys.stdin  = open ("Input.txt")
sys.stdout = open ("Output.txt", "w")

def main():
    for line in sys.stdin:
        print line

main()

This is the closest to my requirement. But this has a problem. If the input is

3
7 4
2 4 6
8 5 9 3

it prints

3

7 4

2 4 6

8 5 9 3

It prints an extra newline after every line. How do I fix this program or whats the best way to solve this problem?

EDIT: Here is the sample run http://ideone.com/8GD0W7


EDIT2: Thanks for the Answer. I got to know the mistake.

import sys
sys.stdin  = open ("Input.txt")
sys.stdout = open ("Output.txt", "w")

def main():
    for line in sys.stdin:
        for data in line.split():
            print data,
        print ""

main()

Changed the program like this and it works as expected. :)

Upvotes: 7

Views: 8678

Answers (1)

mgilson
mgilson

Reputation: 309831

the python print statement adds a newline, but the original line already had a newline on it. You can suppress it by adding a comma at the end:

print line , #<--- trailing comma

For python3, (where print becomes a function), this looks like:

print(line,end='') #rather than the default `print(line,end='\n')`.

Alternatively, you can strip the newline off the end of the line before you print it:

print line.rstrip('\n') # There are other options, e.g. line[:-1], ... 

but I don't think that's nearly as pretty.

Upvotes: 10

Related Questions