Python Program to Reverse the Content of a File using Stack (original) (raw)

Last Updated : 20 Jan, 2026

Given a text file, the task is to reverse the order of its lines using a stack. A stack follows the LIFO (Last In, First Out) principle, meaning the last item added is the first to be removed.

**Example: ****(file.txt)**

This is a World of Geeks.
Welcome to GeeksforGeeks.

**Output:

Welcome to GeeksforGeeks.
This is a World of Geeks.

**Approach

  1. Create an empty stack.
  2. Read each line of the file and push it onto the stack.
  3. Pop each line from the stack and write it back to the file.
  4. The file now contains lines in reverse order.

**Sample Input File:

reverse-file-python

Python `

class Stack: def init(self): self._arr = []

def push(self, val):
    self._arr.append(val)  

def pop(self):
    if self.is_empty():
        return None
    return self._arr.pop()  

def is_empty(self):
    return len(self._arr) == 0  

def reverse_file(filename): S = Stack()

with open(filename, 'r') as original:
    for line in original:
        S.push(line.rstrip("\n"))

with open(filename, 'w') as output:
    while not S.is_empty():
        output.write(S.pop() + "\n")

filename = "file.txt" reverse_file(filename)

with open(filename) as file: for f in file.readlines(): print(f, end="")

`

**Output

This is a World of Geeks.
Welcome to GeeksforGeeks.

**Explanation: