Printing directly from read() in Python adds an extra newline
I've got a Python script that prints out a file to the shell:
开发者_StackOverflow中文版print open(lPath).read()
If I pass in the path to a file with the following contents (no brackets, they're just here so newlines are visible):
> One
> Two
>
I get the following output:
> One
> Two
>
>
Where's that extra newline coming from? I'm running the script with bash on an Ubuntu system.
Use
print open(lPath).read(), # notice the comma at the end.
print
adds a newline. If you end the print
statement with a comma, it'll add a space instead.
You can use
import sys
sys.stdout.write(open(lPath).read())
If you don't need any of the special features of print
.
If you switch to Python 3, or use from __future__ import print_function
on Python 2.6+, you can use the end
argument to stop the print
function from adding a newline.
print(open(lPath).read(), end='')
Maybe you should write:
print open(lPath).read(),
(notice trailing comma at the end).
This will prevent print
from placing a new-line at the end of its output.
精彩评论