Чтение n строк с конца текстового файла с использованием python

Я пытаюсь написать программу для чтения и печати последних n строк текстового файла в python. В моем текстовом файле 74 строки. Я написал функцию, как показано ниже, для чтения последних n строк.

s=74 //Got this using another function, after enumerating the text file
n=5//

def readfile(x):
    print("The total number of lines in the file is",s)
    startline=(s-n)
    print("The last",n,"lines of the file are")
    with open(x,'r') as d:
        for i, l in enumerate(d):
            if (i>=startline):
                print(i)
                print(d.readline())`

Мой желаемый результат:

The total number of lines in the file is 74
The last 5 lines of the file are
69
Resources resembled forfeited no to zealously. 
70
Has procured daughter how friendly followed repeated who surprise. 
71
Great asked oh under on voice downs. 
72
Law together prospect kindness securing six. 
73
Learning why get hastened smallest cheerful.

Но после запуска мой вывод выглядит следующим образом:

The total number of lines in the file is 74
69
Has procured daughter how friendly followed repeated who surprise. 

70
Law together prospect kindness securing six. 

71

Перечисленные индексы не связаны строками и не все напечатаны. Также цикл печатает пробелы для индексов 72 и 73.

если я прокомментирую следующую строку в моей функции:

`#print(d.readline())`  

Мой вывод становится таким:

The total number of lines in the file is 74
The last 5 lines of the file are
69
70
71
72
73

Пробелы исчезли, и все индексы напечатаны. Я не могу понять, почему некоторые индексы и строки не печатаются, когда к функции добавляется print(d.readline()). И почему напечатанный индекс и строки не совпадают.


person zorbamj    schedule 30.06.2019    source источник
comment
Reading n lines from end of text file using python, в этих n строках будут строки с пробелами или нет?   -  person Devesh Kumar Singh    schedule 30.06.2019
comment
Попробуйте прочитать ответы, данные здесь и здесь и здесь   -  person Sheldore    schedule 30.06.2019
comment
Файлы — это итераторы в python. Цикл for выполняется построчно, но d.readline() также считывает другую строку, что заставляет вас пропускать строки. Просто print(l).   -  person Mark    schedule 30.06.2019
comment
@DeveshKumarSingh Вы имели в виду, есть ли в моем файле строки эмоций в конце? Нет. Файл заканчивается на 74-й строке.   -  person zorbamj    schedule 30.06.2019
comment
Почему бы не показать нам, как выглядит ваш файл, и каков ожидаемый пример для данного n   -  person Devesh Kumar Singh    schedule 30.06.2019
comment
@MarkMeyer Спасибо. Это решило мою проблему.   -  person zorbamj    schedule 30.06.2019
comment
@sheldore Я проверил их сейчас. Но моя проблема заключалась в том, почему моя конкретная функция не работала. Например, почему он пропускал строки. Марк Мейер указал на проблему с моим кодом.   -  person zorbamj    schedule 30.06.2019


Ответы (3)


Вы можете сделать это сразу, с помощью readlines() и print(v):

n = 5

with open(x, 'r') as fp:

    lines = fp.readlines()
    total_length = len(lines)
    threshold = total_length - n

    for i, v in enumerate(lines): 
        if i >= threshold:
            print(i, v)
person sashaboulouds    schedule 30.06.2019

Вы можете использовать функцию Python readlines(). чтобы прочитать ваш файл как список строк. Затем вы можете использовать len(), чтобы определить, сколько строк в возвращаемом списке:

n = 5

def readfile(x):
    with open(x) as f_input:
        lines = f_input.readlines()

    total_lines = len(lines)
    print(f"The total number of lines in the file is {total_lines}.")    
    print(f"The last {n} lines of the file are:")

    for line_number in range(total_lines-n, total_lines):
        print(f"{line_number+1}\n{lines[line_number]}",  end='')


readfile('input.txt')

Вы также можете добавить f в качестве префикса к вашей строке, тогда Python интерпретирует строку как содержащую имена переменных, когда она заключена в {}, что упрощает форматирование вашего текста.

person Martin Evans    schedule 30.06.2019

Читать файл дважды кажется немного неэффективным, но, поскольку вы уже это сделали, вы можете легко делать то, что хотите, используя collections.deque следующим образом:

from collections import deque


def print_last_lines(filename, linecount, n):

    # Get the last n lines of the file.
    with open(filename) as file:
        last_n_lines = deque(file, n)

    print("The total number of lines in the file is", linecount)
    print("The last", n, "lines of the file are:")

    for i, line in enumerate(last_n_lines, 1):
        print(linecount-n+i)
        print(line, end='')


filename = 'lastlines.txt'
n = 5

# Count lines in file.
with open(filename) as file:
    linecount = len(list(file))

print_last_lines(filename, linecount, n)
person martineau    schedule 30.06.2019