Python文件内容按行读取到列表中

以文件somefile.txt为例,内容如下:

1
2
3
AAA
BBB
CCC

通常来讲,我们如果只是迭代文件对象每一行,并做一些处理,是不需要将文件对象转成列表的,因为文件对象本身可迭代,而且是按行迭代:

1
2
3
with open('somefile.txt') as f:
for line in f:
print(line, end='')

输出结果:

1
2
3
AAA
BBB
CCC

但如果有什么特别目的,要将文件内容按行转成列表,方法如下。

不去掉行尾的换行符

1
2
with open('somefile.txt') as f:
content = list(f)

或是:

1
2
with open('somefile.txt') as f:
content = f.readlines()

其中,content结果都是没有去掉每一行行尾的换行符的(somefile.txt文件中最后一行本来就没有换行符):

1
['AAA\n', 'BBB\n', 'CCC']

去掉行尾的换行符

1
2
with open('somefile.txt') as f:
content = f.read().splitlines()

或是:

1
2
with open('somefile.txt') as f:
content = [line.rstrip('\n') for line in f]

其中,content结果都是去掉每一行行尾的换行符的:

1
['AAA', 'BBB', 'CCC']

如果,不仅要去掉行尾的换行符,每一行的行首行尾空白字符都要去掉,方法如下:

1
2
with open('somefile.txt') as f:
content = [line.strip() for line in f]

大师兄 wechat
欢迎关注我的微信公众号:Python大师兄