How to skip an extra line of a new line when printing lines read from a file?

I am reading input for my python program from stdin (I assigned a stdin file object). The number of input lines is not known in advance. Sometimes a program can get 1 line, 100 lines, or even no lines.

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 is a problem. If the input signal

 3 7 4 2 4 6 8 5 9 3 

he prints

 3 7 4 2 4 6 8 5 9 3 

It prints an extra line of new line after each line. How to fix this program or how to best solve this problem?

EDIT: Here is an example launch http://ideone.com/8GD0W7


EDIT2: Thanks for the answer. I found out about the error.

 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() 

Such a program has been changed, and it works as expected. :)

+6
source share
1 answer

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

 print line , #<--- trailing comma 

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

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

In addition, before printing, you can disconnect a new line from the end of the line:

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

but I don’t think it is almost as beautiful.

+10
source

Source: https://habr.com/ru/post/946972/


All Articles