2015-03-31 96 views
0

我已經加載的文件到列表Python的不打印正確的結果,雖然結果是正確的

line_storage = []; 

    try: 
     with open(file_name_and_path, 'r') as f: 
      for line in f: 
       line_storage.append(line) # store in list 

但是,試圖將其轉換爲字符串時(「字符串」吧):

total_number_of_lines = len(line_storage) 

lineBuffer = ""; 
for line_index in xrange(0, total_number_of_lines): 
     lineBuffer += line_storage[line_index].rstrip('\n') # append line after removing newline 

該印刷品未顯示完整內容,但僅顯示最後一行。雖然,len(lineBuffer)是正確的。

文件內容是: .... [04.01] Test 1: You should be able to read this. [04.02] Test 2: .... =========================================================== EOF

我如何解決此問題?

回答

2

您的文本行可能以\r\n結尾,而不僅僅是\n。通過刪除\n,您將在每行的末尾保留\r。打印到終端時,每行將覆蓋上一行,因爲\r僅將光標移回當前行的開頭。

該解決方案可能使用.rstrip('\r\n')

+0

或者只是使用不帶任何參數的rstrip – 2015-03-31 22:26:25

+1

@PadraicCunningham:這將刪除任何*空格,並且OP可能希望在行尾保留空格/製表符。 – 2015-03-31 22:27:52