sarah campolt sarah campolt - 7 days ago 5
Python Question

Getting a random word from a text file

I am trying to return a word from a text file (so that I can eventually make a game from the word) but right now I get the error

IndexError: string index out of range


this is what my text file looks like

yellow
awesome
barking
happy
dancing
laughing


and this is the code I currently have

import random

def generate_the_word(infile):

for line in infile.readlines():
random_line = random.randrange(line[0], line[len(line) + 1])

print(random_line)



def main():
infile = open("words.txt","r")
generate_the_word(infile)

infile.close


main()


Do I have the wrong idea about indexing?

Answer

Your for loop is iterating over every line in the file and indexing into that line. You should also take advantage of Python's context managers, which take care of opening and closing files for you. What you want is to load all the lines:

with open(infile) as f:
    contents_of_file = f.read()

Your second problem is that you aren't properly indexing into those lines with randrange. You want a range between 0 and the max number of lines:

lines = contents_of_file.splitlines()
line_number = random.randrange(0, len(lines))
return lines[line_number]

You also need to import the random module before this will run.

Your whole program would look like:

import random

def generate_the_word(infile):
    with open(infile) as f:
        contents_of_file = f.read()
    lines = contents_of_file.splitlines()
    line_number = random.randrange(0, len(lines))
    return lines[line_number]


def main():

    print(generate_the_word("Filename.txt"))


main()

You should also note that reading the file every time is inefficient; perhaps read it once and then pick lines from that. You could, for instance, read it in the main function and pass its already-read values to the generate_the_word function.

Comments