Problem 2.6

Reverse Lines

Write a program reverse.py that takes a filename as command-line argument and prints all the lines in that file in the reverse order.

$ cat files/five.txt
one
two
three
four
five and the last line!

$ python reverse.py files/five.txt
five and the last line!
four
three
two
one

Solution

import sys

filename = sys.argv[1]

lines = open(filename).readlines()[::-1]
for line in lines:
    print(line, end="")