如何将文件逐行读取到列表中?

2022-09-05 00:47:21

如何在Python中读取文件的每一行,并将每一行作为元素存储在列表中?

我想逐行读取文件,并将每行附加到列表的末尾。


答案 1

此代码将整个文件读入内存,并从每行末尾删除所有空格字符(换行符和空格):

with open(filename) as file:
    lines = file.readlines()
    lines = [line.rstrip() for line in lines]

如果您正在处理一个大文件,那么您应该逐行读取和处理它:

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().rstrip()):
        print(line)

根据您计划对文件执行的操作及其编码方式,您可能还需要手动设置访问模式和字符编码:

with open(filename, 'r', encoding='UTF-8') as file:
    while (line := file.readline().rstrip()):
        print(line)

答案 2

请参阅输入和输出

with open('filename') as f:
    lines = f.readlines()

或剥离换行符:

with open('filename') as f:
    lines = [line.rstrip() for line in f]