Write a program to read and display content of file from end to beginning.

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.

Reading a file backward can be achieved by using seek and tell functions to navigate to the end of the file and then read the file backward. Here’s a Python program that reads and displays the content of a file from end to beginning:

def read_file_backward(filename):
        with open(filename, 'r') as file:
            file.seek(0, 2)  # Move the file pointer to the end of the file

            file_size = file.tell()  # Get the current position (end of file)

            # Read the file backward line by line
            for position in range(file_size - 1, -1, -1):
                char = file.read(1)

                if char == '\n':  # Check if we have reached a newline character
                    line = file.readline().rstrip('\n')

            # Read the first line (since the loop skips the first line)
            first_line = file.readline().rstrip('\n')

    except FileNotFoundError:
        print(f"File '{filename}' not found.")

filename = input("Enter the filename: ")


When you run the program, it prompts you to enter the filename. You can provide the name of the file you want to read backward. The program opens the file in read mode and uses seek(0, 2) to move the file pointer to the end of the file. It then retrieves the file size using tell() to determine the position of the last character.

The program then starts reading the file backward from the last character by using a loop and seek() to set the file position. It reads one character at a time and checks if it’s a newline character ('\n'). If a newline character is encountered, it uses readline() to read the line and prints it.

Finally, after the loop completes, the program seeks back to the beginning of the file using seek(0) and reads the first line to ensure it’s not missed.


Leave a Reply

Your email address will not be published. Required fields are marked *