user3400369
user3400369

Reputation: 1

Random word picker

So I am making a function that counts the number of lines in a text file, picks a random line from it and stores it in a variable, this is what I have so far

def word_choice():

    import random

    counter = 0
    counter2 = 0

    inputFile = open('words.txt','r')
    line = inputFile.readline()

    while line:
        line = inputFile.readline()
        counter = counter + 1
    number = random.randint(1,counter)
    inputFile.close()

    Words = open('words.txt','r')

    for counter2 in range(number):
        line = Words.readline()
    return line.rstrip()

but when I run it it keeps coming up with the counter at one, any suggesetions to fix this problem?

Upvotes: 0

Views: 289

Answers (1)

Carter Sande
Carter Sande

Reputation: 1849

You could just use random.choice to pick a random item from the list of words:

    word = random.choice(f.readlines())

Upvotes: 5

Related Questions