import fileinput
import random
# loading the fortunes file as elements of a list;
# using fileinput we don't load the whole file in memory
fortunes = []
for line in fileinput.input(['fortunes.txt']):
if not line.strip() == '': # skip blank lines
fortunes.append(line)
# printing a random fortune:
print "\n" + fortunes[random.randint(0, len(fortunes)-1)]
The file "fortunes.txt" would have for instance the following contents (or e.g. these), separated by blank lines:
Never take life seriously. Nobody gets out alive anyway.
Behind every successful man is a surprised woman. - Maryon Pearson
Hard work never killed anybody, but why take a chance?
I am not a vegetarian because I love animals; I am a vegetarian because I hate plants. A. Whitney Brown
No comments:
Post a Comment