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 file_read_backwards module.

To install it, we run:

pip install file_read_backwards

Then we write:

from file_read_backwards import FileReadBackwards

with FileReadBackwards("file.txt", encoding="utf-8") as frb:
    for l in frb:
        print(l)

to read the file.txt file backwards.

We pass in the file path and the encoding as arguments for the FileReadBackwards constructor.

Then we loop through the iterator with the lines returned.

Therefore, is file.txt has

foo
bar
baz

Then we get:

baz
bar
foo

Conclusion

To read a file in reverse order with Python, we can use the file_read_backwards module.

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 *