Python行结尾' '

时间:2017-08-16 08:10:17

标签: python

此代码

with open('iter.txt') as f:
    try:
        while True:
            line = next(f)
            print(line,end='')
    except StopIteration:
            pass

按预期工作。 但是

    print(line,end='\n')

插入空行。

Iteration is one of Python’s strongest features. At a high level, you might simply view

iteration as a way to process items in a sequence. However, there is so much more that

is possible, such as creating your own iterator objects,

为什么呢? os.linesep还有其他选择吗?

1 个答案:

答案 0 :(得分:1)

据我所知,如果只有你的行不以它结尾,你想要打印一个新行符号(os.linesep),以防止这个额外的空白行。< / p>

可以通过以下检查解决:

import os


with open('iter.txt') as f:
    for line in f:
        # Print with end='' if your line contains a new line
        # Otherwise, print this new line

        linesep = os.linesep
        line_end = '' if linesep in line else linesep

        print(line, end=line_end)