Computer Science
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
3 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
Related Questions
Write a program to read a file 'Story.txt' and create another file, storing an index of 'Story.txt', telling which line of the file each word appears in. If word appears more than once, then index should-show all the line numbers containing the word.
Write a program to accept a filename from the user and display all the lines from the file which contain Python comment character '#'.
Write a Python program to display the size of a file after removing EOL characters, leading and trailing white spaces and blank lines.
Write a function Remove_Lowercase() that accepts two file names, and copies all lines that do not start with lowercase letter from the first file into the second file.