This is a Python Program to read the contents of a file in reverse order.
The program takes a file name from the user and reads the contents of the file in reverse order.
1. Take the file name from the user.
2. Read each line from the file using for loop and store it in a list.
3. Print the elements of list in reverse order.
Here is source code of the Python Program to read the contents of the file in reverse order. The program output is also shown below.
filename=input("Enter file name: ") for line in reversed(list(open(filename))): print(line.rstrip())
1. User must enter a file name.
2. The file is opened using the open() function and all lines are stored in a list.
3. reversed() function produces a reverse iterator.
4. All the lines are then printed in reverse order using a for loop and rstrip() function strips all the blank spaces from the end of the line.
Case 1: Contents of file: hello world hello Output: Enter file name: read.txt hello hello word Case 2: Contents of file: line1 line2 line3 Output: Enter file name: read2.txt line3 line2 line1
Sanfoundry Global Education & Learning Series – Python Programs.
To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.