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

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


当前回答

您也可以在NumPy中使用loadtxt命令。这比genfromttxt检查的条件更少,因此可能更快。

import numpy
data = numpy.loadtxt(filename, delimiter="\n")

其他回答

下面是我用来简化文件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。

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

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

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

使用此项:

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()获取列表。

如果您想从命令行或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

如果文档中也有空行,我希望读取内容并将其通过过滤器以防止空字符串元素

with open(myFile, "r") as f:
    excludeFileContent = list(filter(None, f.read().splitlines()))