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.
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.
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
Conclusion : Try both the programs by yourself and comment down below if you have any issues
0 Comments