A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

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

Python Program to Reverse the Content of a File using Stack

Python Program to Reverse the Content of a File using Stack

Last Updated : 12 Jul, 2025

Given a file, the task is to change the content in reverse order using Stack, as well as store the lines of that file in reverse order in Python.

Examples: 

Input:
1
2
3
4
5
Output:
5
4
3
2
1
Approach to Python Program to Reverse a Stack Using Recursion

Input File:

Code Explanation

Here first we create a stack class and then initialize an array in the class providing and provide the method to an array that follows the LIFO rule of the Python stack. The LIFO rule stands for Last Input Frist Output which is the basic rule of the stack after that we use that stack to store the data of the file and after storing the data we extract the data from the stack and print the data we append in the stack will come out first and like that we get the output data of the file reversed.

Python3
# Creating Stack class (LIFO rule)
class Stack:

    def __init__(self):

        # Creating an empty stack
        self._arr = []

    # Creating push() method.
    def push(self, val):
        self._arr.append(val)

    def is_empty(self):

        # Returns True if empty
        return len(self._arr) == 0

    # Creating Pop method.
    def pop(self):

        if self.is_empty():
            print("Stack is empty")
            return

        return self._arr.pop()

# Creating a function which will reverse
# the lines of a file and Overwrites the
# given file with its contents line-by-line
# reversed


def reverse_file(filename):

    S = Stack()
    original = open(filename)

    for line in original:
        S.push(line.rstrip("\n"))

    original.close()

    output = open(filename, 'w')

    while not S.is_empty():
        output.write(S.pop()+";\n")

    output.close()


# Driver Code
filename = "GFG.txt"

# Calling the reverse_file function
reverse_file(filename)

# Now reading the content of the file
with open(filename) as file:
    for f in file.readlines():
        print(f, end="")

Output:

This is a World of Geeks.
Welcome to GeeksforGeeks.

Time complexity: O(n), where n is the number of lines in the file.
Auxiliary space: O(n), where n is the number of lines in the file.


Python Program to Reverse the Content of a File using Stack


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4