How to choose a random line from a text file

2019-01-25 12:07发布

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?

7条回答
我命由我不由天
2楼-- · 2019-01-25 12:54

Off the top of my head:

import random
def pick_winner(self):
    lines = []
    with open("file.txt", "r") as f:
        lines = f.readlines();
    random_line_num = random.randrange(0, len(lines))
    return lines[random_lines_num]
查看更多
登录 后发表回答