源文件内容如下:

源文件每行后面都有回车,所以用下面输出时,中间会多了一行
>>> try:
with open(r"C:\Users\Administrator\Desktop\20190506biji0.txt" ) as f :
for line in f:
print(line)
except FileNotFoundError:
print("读取文件出错")
hello world
how are you?
I am fine
有两种方法处理:
1.print后面带 end=’’,表示不换行
>>> try:
with open(r"C:\Users\Administrator\Desktop\20190506biji0.txt" ) as f :
for line in f:
print(line,end='')
except FileNotFoundError:
print("读取文件出错")
hello world
how are you?
I am fine
2.用strip()函数去掉每一行的换行符
>>> try:
with open(r"C:\Users\Administrator\Desktop\20190506biji0.txt" ) as f :
for line in f:
line=line.strip('\n')
print(line)
except FileNotFoundError:
print("读取文件出错")
hello world
how are you?
I am fine
再者:
>>> x='''hello world
how are you?
I am fine'''
>>> x.strip('\n')
'hello world\nhow are you?\nI am fine'
>>> print(x,end='')
hello world
how are you?
I am fine
>>> print(x)
hello world
how are you?
I am fine
本文介绍了如何处理Python中文本文件的换行符问题。通过在print语句后使用end=''参数避免换行,或者利用strip()函数去除字符串行尾的换行符。此外,还提供了相关参考链接以供深入学习。
1万+

被折叠的 条评论
为什么被折叠?



