Read a file in reverse
Write a Python program to print the lines of a file in reverse order, and the whole text reversed.
third second first driht dnoces tsrif
Approach
reversed(lines)for line order;[::-1]for characters.
Solution
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])third second first driht dnoces tsrif
Learn the concept
New to this topic? Read the lesson, then come back.