2011-05-25 16 views
0

這裏是文件需要扭轉的文件,但最後一行沒有回車,反向列表所以第一個項目有2條線在它

303620.43,6187793.62 
303663.61,6187757.08 
303652.22,6187702.51 
303580.10,6187685.43 
303551.63,6187737.15 
303574.88,6187775.11 
303610.94,6187773.69 

反轉時,我得到

303610.94,6187773.69303574.88,6187775.11 
303551.63,6187737.15 
303580.10,6187685.43 
303652.22,6187702.51 
303663.61,6187757.08 
303620.43,6187793.62 

我如何確保倒數的最後一行有'\n'

+2

你能告訴我們你的代碼嗎? – 2011-05-25 11:53:27

回答

1

在您的代碼中,讀完一行後,檢查它是否以'\n'結尾。如果沒有,請附上'\n',並繼續進行。

endswith方法可能會派上用場。

5

使用rstrip刪除掉換行(和其它行尾空白)所有線,然後依靠print把它回。

a = [ln.rstrip() for ln in open('datafile.txt')] 
a.reverse() 
for ln in a: 
    print(ln) 
+0

或者如果你沒有編寫將其打印到標準輸出的代碼,那麼當你重新保存文件時,你總是可以重新添加它(例如your_write_handle.write(a +'\ n') – 2011-05-25 12:30:50

+0

謝謝你的工作很好! – 2011-05-25 21:54:23

+0

@Rudy:如果它有效,請點擊答案旁邊的複選標記以接受它 – 2011-05-25 21:54:53

0

+1 larsmans response.An其他的解決辦法是使用字符串對象的拆分方法:

myFile = open(filePath, 'r') 
lines = myFile.read().splitlines() #by default splitlines removes trailing '\n' 
myFile.close() 
lines.reverse() 
for line in lines: 
    print line 
+0

謝謝大家......慢慢掌握Python – 2012-03-25 21:52:18

相關問題