簡體   English   中英

Python無法打印正確的結果,盡管結果正確

[英]Python not printing the correct results, though the results is correct

我已將文件加載到列表中

    line_storage = [];

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

但是,當嘗試將其轉換為字符串(“ stringify”)時:

 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

我該如何解決?

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM