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

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


当前回答

最简单的方法是:

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实现,文件都会被关闭。

其他回答

Python 3.4中引入了pathlib,它有一种非常方便的方法来从文件中读取文本,如下所示:

from pathlib import Path
p = Path('my_text_file')
lines = p.read_text().splitlines()

(splitlines调用将其从包含文件全部内容的字符串转换为文件中的行列表。)

pathlib有很多方便的地方。readtext很好,很简洁,您不必担心打开和关闭文件。如果您只需一次将文件全部读入,这是一个不错的选择。

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。

如果你面对一个非常大/巨大的文件,并且想读得更快(假设你在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)

如果您想从命令行或stdin读取文件,也可以使用fileinput模块:

# reader.py
import fileinput

content = []
for line in fileinput.input():
    content.append(line.strip())

fileinput.close()

将文件传递给它,如下所示:

$ python reader.py textfile.txt 

在此处阅读更多信息:http://docs.python.org/2/library/fileinput.html