English

Reading a file line by line from beginning is a common task, what if you want to read a file backward. This happens when you need to read log files.

Advertisements
Advertisements

Question

Reading a file line by line from 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.

Code Writing
Advertisements

Solution

The file is opened in binary mode and read one byte at a time from the last position towards the beginning. This is suitable for large files because the complete file is not loaded into memory.

def display_backward(filename):
    with open(filename, "rb") as file:
        file.seek(0, 2)
        position = file.tell() - 1

        while position >= 0:
            file.seek(position)
            byte = file.read(1)
            print(byte.decode("utf-8", errors="replace"), end="")
            position -= 1


display_backward("story.txt")

This displays the characters in reverse order. For reverse line order rather than reverse character order, a temporary file or an external indexing technique is generally used.

shaalaa.com
  Is there an error in this question or solution?
Chapter 7: Data File Handling - EXERCISE [Page 146]

APPEARS IN

CBSE Computer Science with Python [English] Class 12
Chapter 7 Data File Handling
EXERCISE | Q 21. | Page 146
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×