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

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


当前回答

如果要包含以下内容:

with open(fname) as f:
    content = f.readlines()

如果不希望包含:

with open(fname) as f:
    content = f.read().splitlines()

其他回答

最简单的方法是:

lines = list(open('filename'))

or

lines = tuple(open('filename'))

or

lines = set(open('filename'))

在set的情况下,我们必须记住,我们没有保留行顺序,并删除重复的行。

下面我添加了@MarkAmery的一个重要补充:

由于您既没有在文件对象上调用.close,也没有使用with语句,因此在某些Python实现中,文件在读取后可能不会关闭,您的进程将泄漏打开的文件句柄。在CPython(大多数人使用的普通Python实现)中,这不是问题,因为文件对象将立即被垃圾收集,这将关闭文件,但通常认为最好的做法是:

with open('filename') as f: lines = list(f) 

以确保无论您使用的是什么Python实现,文件都会被关闭。

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

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

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

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

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

参见输入和输出:

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

或者去掉换行符:

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

具有文本文件内容:

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']