CBSE Today

Print File content in reverse order – Python

The article explains how to output text in reverse order of a Text file using Python. It is assumed that the original file already exists in our directory. The approach is very simple, just open the text file in reading mode and read all the contents of that file in an object.

Example 

Suppose you have a text file that contains

cbsetoday. com is one of the best website.

The output

etis tseb eht fo eno si moc .yadotesbe

Approach to solve this in Python

  1. Read the text file in text mode as all the data of our file is store in text format
  2. Read the contents of a Text file using the read function
  3. Read function read all the data in one go and return in string format
  4. convert this whole data into a list using the split( ) function
  5. Access the whole list of string in reverse order using list slicing method
  6. Reverse the whole list using list slicing
  7. Access one word at a time using for loop in the string
  8. convert this word into its reverse word by using string slicing

The read( ) function read all the content of the text file in string format and return it. The string is further converted into a list and using split( ) function and using reverse function it is displayed on the screen.

The content of the original file used in this program is as follows

My first book was Me and My Family. It gave me chance to be Known to the world. Passing criteria is not always same Same if the line contains p or s

Python code to print reverse of a text file

file = open('C:/python/PracticalFileQuestion/diary.txt', 'r')
data = file.read().split()
for x in data[-1:0:-1]:
    print(x[-1::-1], end=' ')
file.close()

Output of the above program is

s ro p sniatnoc enil eht fi emaS emas syawla ton si airetirc gnissaP .dlrow eht ot nwonK eb ot ecnahc em evag tI .ylimaF yM dna eM saw koob 
tsrif

Hope, this article will help you to understand the basic functionality of list and Text file handling in python

Exit mobile version