如何在Python中读取文件的每一行,并将每一行存储为列表中的元素?
我想逐行读取文件,并将每一行附加到列表的末尾。
如何在Python中读取文件的每一行,并将每一行存储为列表中的元素?
我想逐行读取文件,并将每一行附加到列表的末尾。
当前回答
您可以按照建议简单地执行以下操作:
with open('/your/path/file') as f:
my_lines = f.readlines()
请注意,这种方法有两个缺点:
1) 你把所有的行都存储在内存中。在一般情况下,这是一个非常糟糕的主意。文件可能非常大,内存可能会用完。即使它不大,也只是在浪费内存。
2) 这不允许在读取每行时对其进行处理。因此,如果在这之后处理行,则效率不高(需要两次而不是一次)。
对于一般情况,更好的方法如下:
with open('/your/path/file') as f:
for line in f:
process(line)
您可以任意定义流程函数。例如:
def process(line):
if 'save the world' in line.lower():
superman.save_the_world()
(超人类的实现留给您作为练习)。
这对于任何文件大小都很有效,您只需一次就可以完成文件。这就是一般解析器的工作原理。
其他回答
我会尝试下面提到的方法之一。我使用的示例文件名为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所需的时间几乎相等。
使用此项:
import pandas as pd
data = pd.read_csv(filename) # You can also add parameters such as header, sep, etc.
array = data.values
data是一种数据帧类型,使用值获取ndarray。您还可以使用array.tolist()获取列表。
只需使用splitline()函数。这里有一个例子。
inp = "file.txt"
data = open(inp)
dat = data.read()
lst = dat.splitlines()
print lst
# print(lst) # for python 3
在输出中,您将看到行列表。
如果你面对一个非常大/巨大的文件,并且想读得更快(假设你在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)
将文件行读取到列表中的干净和Python方式
首先也是最重要的一点,你应该专注于以一种高效的方式打开文件并阅读其内容。下面是一个我个人不喜欢的方式的例子:
infile = open('my_file.txt', 'r') # Open the file for reading.
data = infile.read() # Read the contents of the file.
infile.close() # Close the file since we're done using it.
相反,我更喜欢以下打开文件的方法,既可以读也可以写非常干净,不需要关闭文件的额外步骤一旦您使用完它。在下面的语句中,我们将打开文件用于读取,并将其分配给变量infile一旦代码在此语句已完成运行,文件将自动关闭。
# Open the file for reading.
with open('my_file.txt', 'r') as infile:
data = infile.read() # Read the contents of the file into memory.
现在我们需要专注于将这些数据引入Python列表,因为它们是可迭代的、高效的和灵活的。在您的案例中,期望的目标是将文本文件的每一行放入一个单独的元素中。为此,我们将使用splitlines()方法,如下所示:
# Return a list of the lines, breaking at line boundaries.
my_list = data.splitlines()
最终产品:
# Open the file for reading.
with open('my_file.txt', 'r') as infile:
data = infile.read() # Read the contents of the file into memory.
# Return a list of the lines, breaking at line boundaries.
my_list = data.splitlines()
测试我们的代码:
文本文件的内容:
A fost odatã ca-n povesti,
A fost ca niciodatã,
Din rude mãri împãrãtesti,
O prea frumoasã fatã.
打印测试报表:
print my_list # Print the list.
# Print each line in the list.
for line in my_list:
print line
# Print the fourth element in this list.
print my_list[3]
输出(因unicode字符而不同):
['A fost odat\xc3\xa3 ca-n povesti,', 'A fost ca niciodat\xc3\xa3,',
'Din rude m\xc3\xa3ri \xc3\xaemp\xc3\xa3r\xc3\xa3testi,', 'O prea
frumoas\xc3\xa3 fat\xc3\xa3.']
A fost odatã ca-n povesti, A fost ca niciodatã, Din rude mãri
împãrãtesti, O prea frumoasã fatã.
O prea frumoasã fatã.