Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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. :)

like image 756
thefourtheye Avatar asked Jun 10 '13 15:06

thefourtheye


People also ask

How do I get rid of the new line in printing?

x you can add a comma (,) at the end of the print statement that will remove newline from print Python.

How do you skip lines when printing in Python?

The new line character in Python is \n . It is used to indicate the end of a line of text. You can print strings without adding a new line with end = <character> , which <character> is the character that will be used to separate the lines.

How do you print multiple lines on the same line?

To print multiple expressions to the same line, you can end the print statement in Python 2 with a comma ( , ). You can set the end argument to a whitespace character string to print to the same line in Python 3. With Python 3, you do have the added flexibility of changing the end argument to print on the same line.

Does readline read newline?

The readline method reads one line from the file and returns it as a string. The string returned by readline will contain the newline character at the end. This method returns the empty string when it reaches the end of the file.


1 Answers

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.

like image 65
mgilson Avatar answered Sep 21 '22 06:09

mgilson