Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python program to read file and print first two and last two lines of file

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading