2017-08-16 102 views
-1

此代码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有没有其他选择?

+0

文本文件可能已经结束每一行以'\ N',你就加倍了。 – asongtoruin

+0

如何检查它是否以\ n结尾? – MishaVacic

+0

你想让你的最后一行与'end ='''? – wencakisa

回答

1

据我所知,如果只有你的行不以它结束才能防止这个额外的空行,你要打印一个新行符号(os.linesep)。

它可以与这样的检查来解决:

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)