I am trying to write a programme to read and print the last n lines of a text file in python. My text file has 74 lines. I wrote a function like below to read the last n lines.
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())`
My desired output is:
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.
But upon running, my output looks like
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
The enumerated indexes are mismtached with lines and not all are printed. Also the loop is printing white spaces for indices 72 and 73.
if I comment out the following line on my function:
`#print(d.readline())`
My output then becomes:
The total number of lines in the file is 74
The last 5 lines of the file are
69
70
71
72
73
The white spaces are gone and all indices are printed.
I am not able to find out why certain indices and lines are not printed when print(d.readline())
is added to the function. And why the printed index and lines do not match.