python中去掉readline() 的换行符

python使用readline()时读出的内容把换行(\n)也带上了,这并不是我们想要的结果。

示例:

#文本 test.txt
111111
222222
333333
444444
555555
666666

#脚本 readtest.py
#!/usr/bin/python
f = open('test.txt','r')
for i in range(5):
	print(f.readline())

#执行脚本逐行读取结果
[root@localhost ~]# python readtest.py 
111111

222222

333333

444444

555555

去掉换行符:

#第一种
print(f.readline().strip())

#第二种
print(f.readline().split('\n')[0])

#第三种
print(f.readline().replace('\n',''))


#脚本执行的结果
[root@localhost ~]# python readtest.py 
111111
222222
333333
444444
555555

相关文章

Python
使用腾讯云CDN的SDK 用脚本去刷新URL缓存
Python
pip 安装错误 Command "python setup.py egg_info" failed with error code
Python
Linux命令行界面使用Python+Selenium+Chrome对网页截图
Python
warnings.warn('Selenium support for PhantomJS has been deprecated, please use headless
赞赏图片

评论(2)

  • cindy
    cindy Windows 10 Chrome 中国天津天津市电信 回复
    看到代码就头大。。。
    • JockRush
      JockRush 博主 Windows 10 Chrome 中国上海上海市电信 回复
      脑瓜子疼?‍♀️