2017-08-16 79 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)