Fix Python – How to read a file in reverse order?

Question

Asked By – Nimmy

How to read a file in reverse order using python? I want to read a file from last line to first line.

Now we will see solution for issue: How to read a file in reverse order?


Answer

for line in reversed(open("filename").readlines()):
    print line.rstrip()

And in Python 3:

for line in reversed(list(open("filename"))):
    print(line.rstrip())

This question is answered By – Matt Joiner

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0