Categories
Python Answers

How to read a file in reverse order with Python?

Spread the love

Sometimes, we want to read a file in reverse order with Python.

In this article, we’ll look at how to read a file in reverse order with Python.

How to read a file in reverse order with Python?

To read a file in reverse order with Python, we can use the reversed function.

For instance, we write

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

to call open to open the 'filename' file.

Then we call list to convert the iterator to a list.

Next, we call reversed to reverse the list.

And then we use a for loop to loop through the returned lines.

Conclusion

To read a file in reverse order with Python, we can use the reversed function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *