In this article we will discuss an efficient solution to read the contents of a text or CSV file in reverse order i.e. either line by line or get them as a reversed list.

Read a file line by line in reversed order using python

An efficient solution to read a file in reverse order is,

Start reading the file from last and continue till the start of the file i.e. in reverse order. As soon as it encounter any ‘\n’ then it means, a complete line is read. Then yield that line and continue reading in the reverse direction until the top of the file is reached.

We have implemented this logic to a function,

This function accepts the name of the file as an argument and then yields the lines of file from bottom to top.

How does this function work?

It opens the file in binary read mode and moves the cursor to the end of file using file.seek(). Then it starts reading each byte from the end of the file until the start of the file i.e. in reverse direction and save those bytes in a buffer. While reading each byte, as soon as it encounters a new line character ‘\n’, it means a line is read successfully. Then it reverses the buffer and yields the content of buffer i.e. a complete line. After that it re initializes the buffer and continue reading next bytes from the file in reverse direction till the top of the file is reached and keeps on yielding lines till top of file.

Let’s use this function,

Suppose we have a file ‘sample.txt’ and its contents are,

Read the contents of a ‘sample.txt’ in reverse order line by line,

Output:

As we are reading one byte at a time and keeping only last line in buffer, therefore even if the file is large, our solution will be efficient.

Get a list of all lines of file in reversed order using python

Instead of reading line by line, suppose we want to get all the lines of a file as a list but in reverse order.
To do that we have created a function that reads all lines of a file in list and then returns a reversed list,

Let’s use this function to get a reversed list of all lines of a file ‘sample.txt’ and then iterate over that list,

Output:

Here we got all the lines of a file as a list in reverse order, then we iterated over that list.

If you just want to iterate over the lines of a file in reverse order then this is not an efficient solution, because it keeps all the lines in memory and if file is large like in GBs then it will create issues. So, use this solution with small files only and for large files prefer the first solution mentioned above. It was a little complex but was surely an efficient solution.

The complete example is as follows,

Output

Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.