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
- Open the first file by using open(“readcontent.txt”).
- Read the data in the file using read().
- Convert it to a list using list().
- Now reverse the list using reversed().
- 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.