Program to read the content of the file in reverse order

In this python file program, we will read the content of the file in reverse order with the help of the below-given steps. Let’s consider we have readcontent.txt file with the below content.

				
					#readcontent.txt
Line1 : This is India.
Line2 : This is America.
Line3 : This is Canada.
Line4 : This is Australia.

				
			
Steps to solve the program
  1. Open the first file by using open(“readcontent.txt”).
  2. Read the data in the file using read().
  3. Convert it to a list using list().
  4. Now reverse the list using reversed().
  5. Use a for loop to iterate over the lines in the reversed list and print the line.
				
					# Open file
file = open('readcontent.txt')
# Read lines and converting it to a list
data = list(file.readlines())
# Iterate over lines in reverse order
for line in reversed(data):
    print(line)
				
			

Output :

Line4 : This is Australia.

Line3 : This is Canada.

Line2 : This is America.

Line1 : This is India.




move the cursor to a specific position in a file.

Leave a Comment