Read a file in reverse

EasyFile Handling Programs · 33 of 38

Write a Python program to print the lines of a file in reverse order, and the whole text reversed.

Advertisement
Output
third
second
first
driht
dnoces
tsrif

Approach

  1. reversed(lines) for line order; [::-1] for characters.

Solution

Python
with open("story.txt", "w") as f:    f.write("first\nsecond\nthird\n") with open("story.txt") as f:    lines = f.read().splitlines()for line in reversed(lines):    print(line)print("\n".join(lines)[::-1])
Output
third
second
first
driht
dnoces
tsrif
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More file handling programs

← All 38 File Handling Programs