How to choose a random line from a text file

Suit Boy Apps picture Suit Boy Apps · Feb 17, 2013 · Viewed 23.2k times · Source

I am trying to make a lottery program for my school (we have an economic system).

My program generates numbers and saves it off into a text file. When I want to "pull" numbers out of my generator I want it to ensure that there is a winner.

Q: How do I have Python select a random line out of my text file and give my output as that number?

Answer

NPE picture NPE · Feb 17, 2013

How do I have python select a random line out of my text file and give my output as that number?

Assuming the file is relatively small, the following is perhaps the easiest way to do it:

import random
line = random.choice(open('data.txt').readlines())