我有一个Python脚本打印出一个文件到shell:
print open(lPath).read()
Run Code Online (Sandbox Code Playgroud)
如果我将路径传递给具有以下内容的文件(没有括号,它们只是在这里,所以新行是可见的):
> One
> Two
>
Run Code Online (Sandbox Code Playgroud)
我得到以下输出:
> One
> Two
>
>
Run Code Online (Sandbox Code Playgroud)
那个额外的换行来自哪里?我在Ubuntu系统上使用bash运行脚本.
使用
print open(lPath).read(), # notice the comma at the end.
Run Code Online (Sandbox Code Playgroud)
print添加换行符.如果您print使用逗号结束语句,则会添加空格.
您可以使用
import sys
sys.stdout.write(open(lPath).read())
Run Code Online (Sandbox Code Playgroud)
如果你不需要任何特殊功能print.
如果切换到Python 3,或from __future__ import print_function在Python 2.6+上使用,则可以使用该end参数来停止print添加换行符.
print(open(lPath).read(), end='')
Run Code Online (Sandbox Code Playgroud)