Python Practice › File Handling Programs › Program 11
Random line from a file
Write a Python program to read a random line from a file.
Output
Test early
Approach
- Read the lines and use
random.choice; seed for a repeatable demo.
Solution
import random with open("quotes.txt", "w") as f: f.write("Keep it simple\nTest early\nAutomate the boring stuff\nRead the error\n") random.seed(4)with open("quotes.txt") as f: lines = f.read().splitlines()print(random.choice(lines))Output
Test early
Learn the concept
New to this topic? Read the lesson, then come back.