Random line from a file

EasyFile Handling Programs · 11 of 38

Write a Python program to read a random line from a file.

Advertisement
Output
Test early

Approach

  1. Read the lines and use random.choice; seed for a repeatable demo.

Solution

Python
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.

More file handling programs

← All 38 File Handling Programs

Leave a Comment