关于在Python中使用IO读取.txt文件时包含的换行符

我是 Python 的初学者,一直在尝试迄今为止所知道的内容,并遇到了以下问题。有人可以帮助我理解为什么会发生这种情况吗?


假设我有一个名为“test.txt”的文本文件,其中包含以下内容,


This is the first line

This is the second line

This is the third line

我通过执行以下操作来打印此文本文件中的每一行,


with open('test.txt', 'r') as f:

    for line in f:

        print(line)

然而,我们得到的输出是,


This is the first line


This is the second line


This is the third line

如上所示,我们得到一个空行,因为文本文件中的每一行在每一行的末尾都包含一个“\n”。


为了摆脱上面打印的空行,我知道我们可以这样做,


with open('test.txt', 'r') as f:

    for line in f:

        print(line, end='')

这给了我们以下输出,


This is the first line

This is the second line

This is the third line

我不明白的是,我们如何通过在每行末尾添加一个空字符串来摆脱换行符?


Pythonpython-3.x细绳for循环这


慕婉清6462132
浏览 112回答 2
2回答

蝴蝶不菲

请注意,“\n”是赋予 的默认参数end。这是来自官方 python 文档: print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)。您可以在此处查看文档:https ://docs.python.org/3/library/functions.html#print

墨色风雨

python 中的函数的参数print有一个默认值,当您用空字符串覆盖该值时=>您将删除新的行行为。\nend''print(line, end='')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python