Python 正在向输出添加额外的换行符 [英] Python is adding extra newline to the output

查看:58
本文介绍了Python 正在向输出添加额外的换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入文件:a.txt

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc

python代码:

with open("a.txt") as f:对于 f 中的行:印刷线

问题:

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbcccccccccc

如您所见,输出在每个项目之间都有额外的行.

如何防止这种情况发生?

解决方案

print 追加换行符,输入行已经以换行符结束.

标准的解决方案是逐字输出输入行:

导入系统with open("a.txt") as f:对于 f 中的行:sys.stdout.write(行)

PS:对于 Python 3(或带有打印功能的 Python 2),abarnert 的 print(..., end='') 解决方案是最简单的.>

The input file: a.txt

aaaaaaaaaaaa
bbbbbbbbbbb
cccccccccccc

The python code:

with open("a.txt") as f:
    for line in f:
        print line

The problem:

aaaaaaaaaaaa

bbbbbbbbbbb

cccccccccccc

as you can see the output has extra line between each item.

How to prevent this?

解决方案

print appends a newline, and the input lines already end with a newline.

A standard solution is to output the input lines verbatim:

import sys

with open("a.txt") as f:
    for line in f:
        sys.stdout.write(line)

PS: For Python 3 (or Python 2 with the print function), abarnert's print(…, end='') solution is the simplest one.

这篇关于Python 正在向输出添加额外的换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆