简体   繁体   中英

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

I'd like to save text in a .txt file and call on it with

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

f1 = f.readlines()

This returns a list, which seems perfect because I can select which element from the list I want. However, I need to save multiple sentences on one line to group the right sentences. If I want to print one group of sentences on seperate lines, I can't use /n to start a newline when reading from a .txt file. But if I normally define a list with /n in it, it creates a newline no problem. Does anyone know a way around this?

一件事是这是一个列表,您可以在一个位置插入一个项目:

f1.insert(POSITION,"\n")

What you can do is choose a delimiter that won't appear anywhere in your text, and use that to separate each line in your input data file. Then, upon reading each line and before printing it or doing whatever else you want to do with it, replace the delimiters with newlines:

"""
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)

Result:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM