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

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


当前回答

命令行版本

#!/bin/python3
import os
import sys
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
filename = dname + sys.argv[1]
arr = open(filename).read().split("\n") 
print(arr)

运行方式:

python3 somefile.py input_file_name.txt

其他回答

参见输入和输出:

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

我会尝试下面提到的方法之一。我使用的示例文件名为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(filename) as file:
    lines = [line.rstrip() for line in file]

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

with open(filename) as file:
    for line in file:
        print(line.rstrip())

在Python 3.8及以上版本中,可以使用while循环和walrus运算符,如下所示:

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)

如果你面对一个非常大/巨大的文件,并且想读得更快(假设你在TopCoder或HackerBank编码竞赛中),你可以一次将相当大的行块读入内存缓冲区,而不只是在文件级别逐行迭代。

buffersize = 2**16
with open(path) as f:
    while True:
        lines_buffer = f.readlines(buffersize)
        if not lines_buffer:
            break
        for line in lines_buffer:
            process(line)