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

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


当前回答

这将从文件中生成一个“数组”。

lines = tuple(open(filename, 'r'))

open返回一个可以迭代的文件。当您遍历一个文件时,您会从该文件中获取行。tuple可以使用迭代器,并从您给它的迭代器中为您实例化一个tuple实例。

其他回答

参见输入和输出:

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

或者去掉换行符:

with open('filename') as f:
    lines = [line.rstrip('\n') for line in f]
f = open("your_file.txt",'r')
out = f.readlines() # will append in the list out

现在,变量out是您想要的列表(数组)。您可以选择:

for line in out:
    print (line)

Or:

for line in f:
    print (line)

你会得到同样的结果。

具有文本文件内容:

line 1
line 2
line 3

我们可以在上面txt的同一目录中使用此Python脚本

>>> with open("myfile.txt", encoding="utf-8") as file:
...     x = [l.rstrip("\n") for l in file]
>>> x
['line 1','line 2','line 3']

使用追加:

x = []
with open("myfile.txt") as file:
    for l in file:
        x.append(l.strip())

Or:

>>> x = open("myfile.txt").read().splitlines()
>>> x
['line 1', 'line 2', 'line 3']

Or:

>>> x = open("myfile.txt").readlines()
>>> x
['linea 1\n', 'line 2\n', 'line 3\n']

Or:

def print_output(lines_in_textfile):
    print("lines_in_textfile =", lines_in_textfile)

y = [x.rstrip() for x in open("001.txt")]
print_output(y)

with open('001.txt', 'r', encoding='utf-8') as file:
    file = file.read().splitlines()
    print_output(file)

with open('001.txt', 'r', encoding='utf-8') as file:
    file = [x.rstrip("\n") for x in file]
    print_output(file)

输出:

lines_in_textfile = ['line 1', 'line 2', 'line 3']
lines_in_textfile = ['line 1', 'line 2', 'line 3']
lines_in_textfile = ['line 1', 'line 2', 'line 3']

我会尝试下面提到的方法之一。我使用的示例文件名为dummy.txt。您可以在此处找到该文件。我假设该文件与代码位于同一目录中(您可以更改fpath以包含正确的文件名和文件夹路径)。

在下面提到的两个示例中,lst给出了您想要的列表。

1.第一种方法

fpath = 'dummy.txt'
with open(fpath, "r") as f: lst = [line.rstrip('\n \t') for line in f]

print lst
>>>['THIS IS LINE1.', 'THIS IS LINE2.', 'THIS IS LINE3.', 'THIS IS LINE4.']

2.在第二种方法中,可以使用Python标准库中的csv.reader模块:

import csv
fpath = 'dummy.txt'
with open(fpath) as csv_file:
    csv_reader = csv.reader(csv_file, delimiter='   ')
    lst = [row[0] for row in csv_reader] 

print lst
>>>['THIS IS LINE1.', 'THIS IS LINE2.', 'THIS IS LINE3.', 'THIS IS LINE4.']

您可以使用这两种方法之一。两种方法创建lst所需的时间几乎相等。

这比必要的更明确,但可以做到你想要的。

with open("file.txt") as file_in:
    lines = []
    for line in file_in:
        lines.append(line)