CBSE Class 12 Computer Science Question 33 of 43

Practice Paper — Question 4

Back to all questions
4
Question

Question 28(b)

Write a function reverseFile() in Python to read lines from text file 'TESTFILE.TXT' and display the file content in reverse order so that the last line is displayed first and the first line is displayed at the end.

Solution
def reverseFile():
    file = open('TESTFILE.TXT', 'r')
    lines = file.readlines()  
    line_count = len(lines)
    for i in range(line_count - 1, -1, -1):
        print(lines[i].strip()) 
reverseFile()
Output
A marked difference will come in our country.
We all pray for everyone's safety
An apple a day keeps the doctor away.
Answer