How to read a file line-by-line into a list?

Как мне прочитать каждую строку файла в Python и сохранить каждую строку как элемент в списке?

Я хочу прочитать файл построчно и добавить каждую строку в конец списка.

33 ответа

Проверьте этот короткий фрагмент

fileOb=open("filename.txt","r")
data=fileOb.readlines() #returns a array of lines.

или же

fileOb=open("filename.txt","r")
data=list(fileOb) #returns a array of lines.

см. документы для справки

Вы также можете использовать команду loadtxt в NumPy. Это проверяет меньше условий, чем genfromtxt, так что это может быть быстрее.

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

Мне нравится использовать следующее. Чтение строк сразу.

contents = []
for line in open(filepath, 'r').readlines():
    contents.append(line.strip())

Или используя понимание списка:

contents = [line.strip() for line in open(filepath, 'r').readlines()]

Вот вспомогательный класс библиотеки 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.linesили даже превратить его в отдельный метод под названием read_lines,

Версия для командной строки

#!/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
lines = list(open("dict.lst", "r"))
linesSanitized = map(lambda each:each.strip("\n"), lines)
print linesSanitized
with open(fname) as fo:
        data=fo.read().replace('\n', ' ').replace (',', ' ')

Это должно ответить на ваш вопрос. Функция замены будет действовать как разделитель для удаления файла.

textFile = open("E:\Values.txt","r")
textFileLines = textFile.readlines()

"textFileLines" - это массив, который вы хотели

Как насчет:

fp = open("filename")
content = fp.read();
lines = content.split("\n")
Другие вопросы по тегам