Python Program to Print the Contents of File in Reverse Order

This is a Python Program to read the contents of a file in reverse order.

Problem Description

The program takes a file name from the user and reads the contents of the file in reverse order.

Problem Solution

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.
4. Exit.

Program/Source Code

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())
Program Explanation

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.

advertisement
advertisement
Runtime Test Cases
 
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.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.