今天爱分享给大家带来Python读一个文件如何获取每一行内容(不包括换行符)【面试题详解】,希望能够帮助到大家。
读一个文件,如何获取每一行内容(不包括换行符)
比较pythonic的做法:
>>> text = "line 1\nline 2\r\nline 3\nline 4" >>> text.splitlines() ['line 1', 'line 2', 'line 3', 'line 4']
用rstrip,(rstrip/lstrip/strip)
#去除了尾部的空白+换行
>>> 'test string \n'.rstrip()
'test string'
#只去换行
>>> 'test string \n'.rstrip('\n')
'test string '
#更通用的做法,系统相关
>>> import os, sys
>>> sys.platform
'linux2'
>>> "foo\r\n".rstrip(os.linesep)
'foo\r'
原文链接:https://blog.itblood.com/4396.html,转载请注明出处。

![邻居的人妻2~在丈夫身旁忘我中出SEX 官方中文版+步兵补丁 [4.3G] [互动SLG/中文/动态/NTL]](/wp-content/uploads/replace/2025/10/18/0398170a0ed8334144dc1164f97737fb.webp)