Reputation: 1
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
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