Reputation: 14694
I want to do the following, I want to read a txt file line by line and then print the input to the console, So i have the following input.txt
:
1
2
3
and the python code looks like this:
file = open("input.txt")
for line in file:
print line
why I get a output like:
1
2
3
and not:
1
2
3
how to avoid this?
Upvotes: 1
Views: 117
Reputation: 304443
The print
function in Python3 lets you suppress the line ending. In Python2.6+ you can import the print function from the __future__
module
from __future__ import print_function # required for Python2
file = open("input.txt")
for line in file:
print(line, end="")
Upvotes: 2
Reputation: 133724
for line in file:
print line
print
prints some text and then also prints a '\n'
new line after it. You can use a trailing comma to stop this:
for line in file:
print line,
Or just .rstrip()
it:
for line in file:
print line.rstrip('\n')
Upvotes: 3