|
Description:
This procedure reads through a file of unknown size once, returning a random line from the file.
Source: Text Source
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 != "":
if random.uniform(0,lineNum)<1:
it = aLine
else:
break
fh.close()
return it
Discussion:
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.
|