如何在 Python 中读取文件的每一行并将每一行作为一个元素存储在列表中?
我想逐行读取文件并将每一行附加到列表的末尾。
此代码会将整个文件读入内存:
with open(filename) as file: lines = file.readlines()
如果要删除每行末尾的所有空白字符(换行符和空格),请改用:
with open(filename) as file: lines = [line.rstrip() for line in file]
(这避免了从 分配额外的列表file.readlines()。)
file.readlines()
如果您正在处理一个大文件,那么您应该逐行阅读和处理它:
with open(filename) as file: for line in file: print(line.rstrip())
在 Python 3.8 及更高版本中,您可以使用带有海象运算符的 while 循环,如下所示:
with open(filename) as file: while line := file.readline(): print(line.rstrip())
请参阅输入和输出:
with open('filename') as f: lines = f.readlines()
或剥离换行符:
with open('filename') as f: lines = [line.rstrip('\n') for line in f]