Python - Display the Contents of a Text File in Reverse Order?


We will display the contents of a text file in reverse order. For that, let us first create a text file amit.txt with the following content 


Display the contents of a text file in Reverse Order with Slicing

Example

Let us now read the contents of the above file in reverse order −

# The file to be read with open("amit.txt", "r") as myfile: my_data = myfile.read() # Reversing the data by passing -1 for [start: end: step] rev_data = my_data[::-1] # Displaying the reversed data print("Reversed data = ",rev_data)

Output

Reversed data = !tisisihT

Display the contents of a text file in Reverse Order by Looping

Example

# Opening the file to read my_data = open('amit.txt','r') # reversing the data for myLine in my_data: l = len(myLine) rev_data = '' while(l>=1): rev_data = rev_data + myLine[l-1] l=l-1 print("Reversed data = ",rev_data) # Displaying the reversed data

Output

Reversed data = !tisisihT

Updated on: 15-Sep-2022

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements