gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:11:46 24 4
gpt4 key购买 nike

我有一个 Python 脚本可以将文件打印到 shell:

print open(lPath).read()

如果我将路径传递给具有以下内容的文件(没有括号,它们就在这里,所以换行符可见):

> One
> Two
>

我得到以下输出:

> One
> Two
>
>

额外的换行符从何而来?我在 Ubuntu 系统上使用 bash 运行脚本。

最佳答案

使用

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

关于python - 在 Python 中直接从 read() 打印会添加一个额外的换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7327911/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com