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.