关于 .txt 文件在使用 Python 中的 IO 读取它们时包含的换行符
Regarding the new line characters .txt files contains when we are reading them in using the IO in Python
我是 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
我不明白的是,我们如何通过在每行末尾添加一个空字符串来摆脱换行符?
请注意,'\n' 是 end
的默认参数。
这是来自官方 python 文档:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
.
您可以在此处查看文档:https://docs.python.org/3/library/functions.html#print
python 中的 print
函数的参数 end
的默认值为 \n
,当您用空字符串 ''
覆盖该值时=> print(line, end='')
你删除了换行行为。
我是 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
我不明白的是,我们如何通过在每行末尾添加一个空字符串来摆脱换行符?
请注意,'\n' 是 end
的默认参数。
这是来自官方 python 文档:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
.
您可以在此处查看文档:https://docs.python.org/3/library/functions.html#print
python 中的 print
函数的参数 end
的默认值为 \n
,当您用空字符串 ''
覆盖该值时=> print(line, end='')
你删除了换行行为。