簡體   English   中英

使用 .readlines() 從 txt 文件讀取時,如何插入換行符?

[英]When reading from txt file with .readlines(), how to insert newline?

我想將文本保存在 .txt 文件中並調用它

f = open("test.txt", "r")

f1 = f.readlines()

這將返回一個列表,這看起來很完美,因為我可以從我想要的列表中選擇哪個元素。 但是,我需要在一行中保存多個句子以對正確的句子進行分組。 如果我想在單獨的行上打印一組句子,從 .txt 文件讀取時,我不能使用 /n 開始換行。 但是如果我通常定義一個帶有 /n 的列表,它會創建一個換行符,沒問題。 有誰知道解決這個問題的方法?

一件事是這是一個列表,您可以在一個位置插入一個項目:

f1.insert(POSITION,"\n")

您可以做的是選擇一個不會出現在文本中任何位置的分隔符,並使用它來分隔輸入數據文件中的每一行。 然后,在閱讀每一行和打印之前,或者做任何你想做的事情之前,用換行符替換分隔符:

"""
Data in the file '/tmp/test.txt':
Now is the time|for all good men|to come to the aid|of their country.
Jack and Jill went|up the hill to fetch|a pail of water.
"""

with open("/tmp/test.txt", "r") as f:
    for line in f.readlines():
        if not line.strip():
            continue
        line = line.replace('|', '\n')
        print(line)

結果:

Now is the time
for all good men
to come to the aid
of their country.

Jack and Jill went
up the hill to fetch
a pail of water.

暫無
暫無

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

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