Welcome, guest | Sign In | My Account | Store | Cart

This procedure reads through a file of unknown size once, returning a random line from the file.

Python, 22 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import random

def randomLine(filename):
	"Retrieve a  random line from a file, reading through the file once"
	fh = open(filename, "r")
	lineNum = 0
	it = ''

	while 1:
		aLine = fh.readline()
		lineNum = lineNum + 1
		if aLine != "":
			#
			# How likely is it that this is the last line of the file ? 
			if random.uniform(0,lineNum)<1:
				it = aLine
		else:
			break

	fh.close()

	return it

Useful, when writing hangman, as a means of selecting random words from dictionary files!

A more obvious approach might be to read the file into an list via readlines() then select a random line from the list. This recipe, however, avoids reading the whole file into memory.