How to Read Reversed Contents of a File in Python


This example will teach us how to output the opposite reading order at the contents of the file sequentially in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

fileName = input("Enter the name of the file with .txt extension: ")
with open(fileName, 'r') as file:
    for line in reversed(list(file)):
        print(line.rstrip())
The content of test1.txt is:
line1
line2
line3

Output:

Enter the name of the file with .txt extension: test1.txt
line3
line2
line1
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments