简体   繁体   English

使用 .readlines() 从 txt 文件读取时,如何插入换行符?

[英]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我想将文本保存在 .txt 文件中并调用它

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.如果我想在单独的行上打印一组句子,从 .txt 文件读取时,我不能使用 /n 开始换行。 But if I normally define a list with /n in it, it creates a newline no problem.但是如果我通常定义一个带有 /n 的列表,它会创建一个换行符,没问题。 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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