Я пытаюсь написать программу для чтения и печати последних 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())
. И почему напечатанный индекс и строки не совпадают.
Reading n lines from end of text file using python
, в этих n строках будут строки с пробелами или нет? - person Devesh Kumar Singh   schedule 30.06.2019d.readline()
также считывает другую строку, что заставляет вас пропускать строки. Простоprint(l)
. - person Mark   schedule 30.06.2019