VOOZH about

URL: https://www.geeksforgeeks.org/python/python-program-to-reverse-the-content-of-a-file-using-stack/

⇱ Python Program to Reverse the Content of a File using Stack - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python Program to Reverse the Content of a File using Stack

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

Output

This is a World of Geeks.
Welcome to GeeksforGeeks.

Explanation:

  • S = Stack(): Creates the stack for storing lines.
  • for line in original: Iterates over lines in the file.
  • S.push(line.rstrip("\n")): Pushes lines onto the stack, stripping newline characters.
  • open(filename, 'w'): Opens the file to overwrite with reversed content.
  • while not S.is_empty(): Continues until all lines are popped.
  • output.write(S.pop() + "\n"): Pops each line and writes it back in reverse order.
  • for f in file.readlines(): Reads all lines to print them.

Related Articles:

Comment