Im writing a program where the user inputs a file name and then the output reads the file and prints the first 2 and the last 2 lines of the file only. I have worked out how to print the first two lines and I have tried to print the last two lines of the file but have hit a hiccup. Is anyone able to explain what I did wrong?
f1 = open(input("Source file name: "))
line1= f1.readline()
line2= f1.readline()
line12= f1.readline()
line13= f1.readline()
print("Output:",line1,line2,line12[-1],line13[-2], sep= "")
f1.close()
the file is 13 lines long so the output should be as followed
output:
line 1
line 2
line 12
line 13
>Solution :
You’re reading the first 4 lines. You need to read through all of them and keep only the last two.
This code reads through all of them, saving the last two lines read:
line1 = f1.readline()
line2 = f1.readline()
last1, last2 = f1.readline(), f1.readline()
while True:
line = f1.readline()
if not line: # eof
break
last1, last2 = line, last1
print("Output:",line1,line2,last2,last1, sep= "")
For example, with a file test.txt:
Line1
line2
Line3
line4
Line5
line6
last line, line 7
You get:
Output:Line1
line2
line6
last line, line 7