Opening random line from file with random.shuffle()

Sean 'Shaleh' Perry shalehperry at attbi.com
Wed Feb 13 21:10:02 EST 2002


On 14-Feb-2002 synthespian wrote:
> 
> 
> Hello-
> 
>       I need to get a random line from a file. I read in thins NG about a
"poorly"
> documented random.shuffle(), but I can't get it to work:
> 

>>> f = open('/home/shaleh/apt.howto')
>>> lines = f.readlines()
>>> import random
>>> random.choice(lines)
'Apt is a suite of utilities that assist the admin in maintaining an\n'

random.choice() is really cool.  Give it any sequence (list, tuple, things that
act like a sequence, etc) and it chooses one item and returns it.  You could
ask for a random card from a list of cards, name in a list of names, etc.




More information about the Python-list mailing list