Menu Close

Retrieving random lines from a file

A little class to retrieve a random line from a file.


import linecache, random

"""
This class will retrieve a random line from a file.

"""
class RandomRetriever:
"""Retrieve a random line from a file.
It caches the file, so it runs fast when used again"""
def __init__(self, fileName=None):
self.fileName = fileName
self.lineCount = self.countLine()

def countLine(self):
lines = 0
try:
fileLines = open(self.fileName, 'r')
except IOError:
print "Cannot open "+self.fileName+" for reading"
for line in fileLines:
lines += 1
return lines

"""Retrieves a random item from the file in this class.

return A random line from the text file.
"""
def randomItem(self):
lineNumber = random.randint(1,self.lineCount)
return linecache.getline(self.fileName, lineNumber).rstrip()

.