直接从Python中的read()打印添加了一个额外的换行符

时间:2011-09-07 01:18:42

标签: python file-io

我有一个Python脚本可以将文件输出到shell:

print open(lPath).read()

如果我将路径传递给包含以下内容的文件(没有括号,它们就在这里,因此可以看到换行符):

> One
> Two
> 

我得到以下输出:

> One
> Two
> 
> 

额外的换行来自哪里?我在Ubuntu系统上使用bash运行脚本。

2 个答案:

答案 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在输出结尾处放置换行符。