Write a Python Program to Reverse The Content of a File And Store it in Another File

Hi, in this blog let's learn how to write a python program to read the contents of a file, reverse the content and write the reversed contents into another file.

Let's assume sample.txt is a file that you are passing it to a Python program and you want to get this file reversed and store the reversed Content into another file i.e, new.txt.

 

Write a Python Program to Reverse The Content of a File And Store it in Another File

 

 

Python Program to Reverse The Content of a File And Store it in Another File

Let's open the file sample.txt in the read mode and read the data into a variable named as text.  Now take the text variable and use string slicing to reverse the contents of the string variable that is the contents of the file gets reversed.  once you get the reversed content just open the new.txt file in the write mode and use write() function to write the data in to new text file and close it.


fd_read = open("sample.txt", "r")
text = fd_read.read()
fd_read.close()
fd_write = open("new.txt", "w")
fd_write.write(text[::-1])
fd_write.close()


Python Program to Reverse The Content of a File And Store it in Another File using with keyword

We can also write the above program using a with keyword the specialty of with keyword is it automatically closes the file upon the local code exit.  User don't need to close the the file explicitly using close() function call

The program is given below

with open("sample.txt", "r") as fd_read, open("new.txt", "w") as fd_write:
    text = fd_read.read()
    fd_write.write(text[::-1])


Conclusion : Try both the programs by yourself and comment down below if you have any issues

 

Post a Comment

0 Comments