reading from a text file

Esmail ebonak at hotmail.com
Mon Nov 30 08:34:08 EST 2009


baboucarr sanneh wrote:
>
> i would like to create a python program that would read from a text file 
> and returns one result at random.


#!/usr/bin/env python

# assuming the file fits into memory, and you are interested in
# random lines

from random import randrange

f = open('data.txt')
data = f.readlines()
number = len(data)
pick = randrange(0, number)
print data[pick]


should do the trick.

Esmail




More information about the Python-list mailing list