Open In App

Python Program to Reverse the Content of a File using Stack

Last Updated : 02 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • Create an empty stack. 
  • One by one push every line of the file to the stack. 
  • One by one pop each line from the stack and put them back to the file.  

Input File:

reverse-file-python

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.



Previous Article
Next Article

Similar Reads

Python program to reverse the content of a file and store it in another file
Given a text file. The task is to reverse as well as stores the content from an input file to an output file. This reversing can be performed in two types. Full reversing: In this type of reversing all the content gets reversed. Word to word reversing: In this kind of reversing the last word comes first and the first word goes to the last position.
2 min read
Python - Copy all the content of one file to another file in uppercase
In this article, we are going to write a Python program to copy all the content of one file to another file in uppercase. In order to solve this problem, let's see the definition of some important functions which will be used: open() - It is used to open a file in various modes like reading, write, append, both read and write.write() - It is used t
2 min read
Python program to reverse a stack
The stack is a linear data structure which works on the LIFO concept. LIFO stands for last in first out. In the stack, the insertion and deletion are possible at one end the end is called the top of the stack. In this article, we will see how to reverse a stack using Python. Algorithm: Define some basic function of the stack like push(), pop(), sho
3 min read
Read content from one file and write it into another file
Prerequisite: Reading and Writing to text files in Python Python provides inbuilt functions for creating, writing, and reading files. Two types of files can be handled in python, normal text files and binary files (written in binary language,0s, and 1s). Text files: In this type of file, Each line of text is terminated with a special character call
2 min read
Find maximum in stack in O(1) without using additional stack in Python
The task is to design a stack which can get the maximum value in the stack in O(1) time without using an additional stack in Python. Examples: Input: Consider the following SpecialStack 16 –> TOP29151918When getMax() is called it should return 29, which is the maximum element in the current stack. If we do pop two times on stack, the stack becom
3 min read
Python program to modify the content of a Binary File
Given a binary file that contains some sentences (space separated words), let's write a Python program to modify or alter any particular word of the sentence. Approach:Step 1: Searching for the word in the binary file. Step 2: While searching in the file, the variable “pos” stores the position of file pointer record then traverse(continue) reading
3 min read
Python program to Reverse a single line of a text file
Given a text file. The task is to reverse a single line of user's choice from a given text file and update the already existing file. Examples: Input: Hello Geeks for geeks! User choice = 1 Output: Hello Geeks geeks! for Input: This is a geek Welcome to GeeksforGeeks GeeksforGeeks is a computer science portal User choice = 0 Output: geek a is This
2 min read
Python Program to Get the File Name From the File Path
In this article, we will be looking at the program to get the file name from the given file path in the Python programming language. Sometimes during automation, we might need the file name extracted from the file path. Better to have knowledge of: Python OS-modulePython path moduleRegular expressionsBuilt in rsplit()Method 1: Python OS-moduleExamp
4 min read
Python - Append content of one text file to another
Having two file names entered by users, the task is to append the content of the second file to the content of the first file with Python. Append the content of one text file to anotherUsing file objectUsing shutil moduleUsing fileinput moduleSuppose the text files file1.txt and file2.txt contain the following data. file1.txt file2.txt Append the c
3 min read
Upload file and read its content in cherrypy python
CherryPy is a web framework of Python which provides a friendly interface to the HTTP protocol for Python developers. It is also called a web application library. It allows developers to build web applications in much the same way they would build any other object-oriented Python program. This results in smaller source code developed in less time.
3 min read