输出到终端时如何使用适当的换行符显示 .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())
我正在编写一个相对基本的打字测试脚本,以便在终端中 运行。我有一个示例文本块,保存为 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())