2011-09-07 103 views
1

我有一个打印出一个文件到外壳Python脚本:打印从Python中的read()增加了一个额外的换行符

print open(lPath).read() 

如果我在的路径传递到一个文件中有以下内容(没有括号,他们只是在这里这么换行符可见):

> One 
> Two 
> 

我得到以下输出:

> One 
> Two 
> 
> 

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

回答

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='') 
+0

谢谢,我是Python新手! –

1

也许你应该写:

print open(lPath).read(), 

(通知在末尾的尾随逗号)。

这会阻止print在其输出结尾处放置一条新线。

相关问题