将文件内容逐行读入列表的例子:

下面的例子,读取一个名为 test.txt 的文件内容,并存入一个列表中。

test.txt 位于与我的python 程序同一个目录下,其内容为:

This is line 1
This is line 2

我的程序如下:

mylist = []

myfile = open('test.txt')

line = myfile.readline()

while line:    
    current_line = line.strip()
    mylist.append(current_line)
    line = myfile.readline()

myfile.close()

print ( mylist[0])
print ( mylist[1])

运行结果如下:

This is line 1
This is line 2