KnowledgeBoat Logo

Class - 12 CBSE Computer Science Important File Handling Questions 2025

Reading a file line by line from the beginning is a common task. What if you want to read a file backward ? This happens when you need to read log files. Write a program to read and display content of file from end to beginning.

Python Data Handling

2 Likes

Answer

Let the file "logs.txt" include the following sample text:

[2022-04-15 10:00:00] INFO: Application started
[2022-04-15 10:05:00] ERROR: Database connection failed
[2022-04-15 10:10:00] WARNING: Disk space low
[2022-04-15 10:15:00] INFO: User logged in: username=john, ip_address=192.168.1.100
file_name = input("Enter the filename: ")
f = open(file_name, 'r')
lines = f.readlines()
for line in lines[::-1]:
    print(line.rstrip())  
f.close()
Output
Enter the filename: logs.txt 
[2022-04-15 10:15:00] INFO: User logged in: username=john, ip_address=192.168.1.100
[2022-04-15 10:10:00] WARNING: Disk space low
[2022-04-15 10:05:00] ERROR: Database connection failed
[2022-04-15 10:00:00] INFO: Application started

Answered By

2 Likes