我有一个Python脚本可以将文件输出到shell:
print open(lPath).read()
如果我将路径传递给包含以下内容的文件(没有括号,它们就在这里,因此可以看到换行符):
> One
> Two
>
我得到以下输出:
> One
> Two
>
>
额外的换行来自哪里?我在Ubuntu系统上使用bash运行脚本。
答案 0 :(得分:8)
使用
print open(lPath).read(), # notice the comma at the end.
print
添加换行符。如果您使用逗号结束print
语句,则会添加空格。
您可以使用
import sys
sys.stdout.write(open(lPath).read())
如果您不需要print
。
如果切换到Python 3,或在Python 2.6+上使用from __future__ import print_function
,则可以使用end
参数来阻止print
函数添加换行符。
print(open(lPath).read(), end='')
答案 1 :(得分:1)
也许你应该写:
print open(lPath).read(),
(注意最后的尾随逗号)。
这将阻止print
在输出结尾处放置换行符。