当输出到终端时,如何用正确的换行符显示.txt文件中的文本



我正在编写一个相对基本的打字测试脚本,以便在终端中运行。我有一个保存为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
'abcndefnII'
>>> 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())

最新更新