如何在Python中读取文件的每一行,并将每一行存储为列表中的元素?
我想逐行读取文件,并将每一行附加到列表的末尾。
如何在Python中读取文件的每一行,并将每一行存储为列表中的元素?
我想逐行读取文件,并将每一行附加到列表的末尾。
当前回答
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)
你会得到同样的结果。
其他回答
下面是我用来简化文件I/O的Python(3)助手库类:
import os
# handle files using a callback method, prevents repetition
def _FileIO__file_handler(file_path, mode, callback = lambda f: None):
f = open(file_path, mode)
try:
return callback(f)
except Exception as e:
raise IOError("Failed to %s file" % ["write to", "read from"][mode.lower() in "r rb r+".split(" ")])
finally:
f.close()
class FileIO:
# return the contents of a file
def read(file_path, mode = "r"):
return __file_handler(file_path, mode, lambda rf: rf.read())
# get the lines of a file
def lines(file_path, mode = "r", filter_fn = lambda line: len(line) > 0):
return [line for line in FileIO.read(file_path, mode).strip().split("\n") if filter_fn(line)]
# create or update a file (NOTE: can also be used to replace a file's original content)
def write(file_path, new_content, mode = "w"):
return __file_handler(file_path, mode, lambda wf: wf.write(new_content))
# delete a file (if it exists)
def delete(file_path):
return os.remove() if os.path.isfile(file_path) else None
然后使用FileIO.lines函数,如下所示:
file_ext_lines = FileIO.lines("./path/to/file.ext"):
for i, line in enumerate(file_ext_lines):
print("Line {}: {}".format(i + 1, line))
请记住,mode(默认为“r”)和filter_fn(默认为检查空行)参数是可选的。
您甚至可以删除read、write和delete方法,只保留FileIO.line,甚至将其转换为一个单独的方法read_lines。
将文件行读取到列表中的干净和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ã.
使用此项:
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()获取列表。
这比必要的更明确,但可以做到你想要的。
with open("file.txt") as file_in:
lines = []
for line in file_in:
lines.append(line)
大纲和摘要
使用文件名,从Path(filename)对象处理文件,或直接将open(filename)作为f,执行以下操作之一:
列表(fileinput.input(文件名))使用path.open()作为f,调用f.readlines()列表(f)path.read_text().splitline()path.read_text().splitlines(keepends=True)迭代fileinput.input或f和list.append每行一次将f传递给绑定的list.extend方法在列表理解中使用f
我将在下面解释每一个的用例。
在Python中,如何逐行读取文件?
这是一个很好的问题。首先,让我们创建一些示例数据:
from pathlib import Path
Path('filename').write_text('foo\nbar\nbaz')
文件对象是惰性迭代器,所以只需对其进行迭代。
filename = 'filename'
with open(filename) as f:
for line in f:
line # do something with the line
或者,如果您有多个文件,请使用另一个惰性迭代器fileinput.input。只有一个文件:
import fileinput
for line in fileinput.input(filename):
line # process the line
或者对于多个文件,向其传递文件名列表:
for line in fileinput.input([filename]*2):
line # process the line
同样,上面的f和fileinput.input都是/return惰性迭代器。您只能使用一次迭代器,因此为了在提供函数代码的同时避免冗长,我将在此处使用稍微简洁的fileinput.input(文件名)。
在Python中,如何将文件逐行读入列表?
啊,但出于某种原因,你想把它列在列表中?如果可能的话,我会避免。但如果你坚持。。。只需将fileinput.input(文件名)的结果传递给列表:
list(fileinput.input(filename))
另一个直接的答案是调用f.readlines,它返回文件的内容(最多为可选的提示字符数,因此您可以这样将其分解为多个列表)。
您可以通过两种方式访问此文件对象。一种方法是将文件名传递给打开的内置程序:
filename = 'filename'
with open(filename) as f:
f.readlines()
或者使用pathlib模块中的新Path对象(我已经非常喜欢它,并将从这里开始使用):
from pathlib import Path
path = Path(filename)
with path.open() as f:
f.readlines()
list还将使用文件迭代器并返回一个列表-这也是一个非常直接的方法:
with path.open() as f:
list(f)
如果您不介意在拆分之前将整个文本作为一个字符串读入内存,那么可以使用Path对象和splitlines()字符串方法将其作为一行代码。默认情况下,拆分线会删除换行符:
path.read_text().splitlines()
如果要保留换行符,请传递keepends=True:
path.read_text().splitlines(keepends=True)
我想逐行读取文件,并将每一行附加到列表的末尾。
现在,考虑到我们已经用几种方法轻松地演示了最终结果,这一要求有点愚蠢。但在列出列表时,您可能需要对行进行筛选或操作,所以让我们来幽默一下这个请求。
使用list.append可以在附加每一行之前对其进行筛选或操作:
line_list = []
for line in fileinput.input(filename):
line_list.append(line)
line_list
使用list.extend会更直接一些,如果您有一个预先存在的列表,可能会有用:
line_list = []
line_list.extend(fileinput.input(filename))
line_list
或者更惯用地说,我们可以使用列表理解,并根据需要在其中进行映射和过滤:
[line for line in fileinput.input(filename)]
或者更直接地,要关闭圆,只需将其传递到列表即可直接创建新列表,而无需对行进行操作:
list(fileinput.input(filename))
结论
您已经看到了许多将文件中的行放入列表的方法,但我建议您避免将大量数据具体化到列表中,而是尽可能使用Python的惰性迭代来处理数据。
也就是说,首选fileinput.input或path.open()作为f。