簡體   English   中英

輸出到終端時如何使用適當的換行符顯示 .txt 文件中的文本

[英]How to display text from a .txt file with proper line breaks when output to terminal

我正在編寫一個相對基本的打字測試腳本以在終端中運行。 我有一個保存為text_block.txt的示例文本塊:

Roads go ever ever on,
Over rock and under tree,
By caves where never sun has shone,
By streams that never find the sea;
Over snow by winter sown,
And through the merry flowers of June,
Over grass and over stone,
And under mountains in the moon.

以及以下函數來讀取它:

def load_text():
    with open("text_block.txt", "r") as f:
        lines = []
        for line in f:
            lines.append(line.strip())
        lines = ''.join(lines)
        return lines

在終端中顯示時給出以下內容:

Roads go ever ever on,Over rock and under tree,By caves where never sun has shone,By streams that never find the sea;Over snow by winter sown,And through the merry flowers of June,Over grass and over stone,And under mountains in the moon.

我如何讓它有適當的換行符來模仿文本文件的格式?

您可以通過在所有單詞之間插入換行符來獲得所需的輸出:

a = ["abc", "deg", "II"]
b = "\n".join(a)
>>> b
'abc\ndef\nII'
>>> print(b)
abc
deg
II

但是,您可能希望在末尾添加換行符,在這種情況下,只需添加:

b += "\n"
>>> print(b)
abc
deg
II

但是您也可以改進您的代碼。 您可以使用列表理解來刪除一些額外的行(它與您的示例相同)。

with open() as f:
    return "".join([for line in f])

刪除.strip()將保留文件中的所有內容(包括現有的換行符)。

或更短:

with open() as f:
    return "".join(f.readlines())

暫無
暫無

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

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