It could be as simple as:

import random
print(random.choice(open("WordsForGames.txt").readline().split()))

The words are read from the first line of the file and converted into an array, then a random choice is made from that array.

If the words are instead on separate lines (or spread across lines), use read() instead of readline().

Answer from paxdiablo on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › pulling-a-random-word-or-string-from-a-line-in-a-text-file-in-python
Pulling a random word or string from a line in a text file in Python - GeeksforGeeks
July 23, 2025 - Read all the text from the file and store in a string · Split the string into words separated by space. Use random.choice() to pick a word or string. ... # Python code to pick a random # word from a text file import random # Open the file in ...
Discussions

Selecting a random word from text file?
The easiest way would be to use the split() function. Split() takes a string and returns an array of strings split up by user a character or string as a delimiter. In your case it would be very simple. String text = "Your text goes here."; String words[] = split(text, " "); This will however keep punctuation attached to any words. It may beyond your skill right now, but these sorts of problems are very easily solved by what is called a regular expression, or regex. As always, Shiffman has a pretty good video and guide on them. Essentially regex's are like using "find" in Word but on steroids. Edit: just realised this is only half the answer. To select a random word from our new words array we can simply do: String word = words[int(random(words.length))]; This might be a bit complicated looking at first but all we're doing is randomly generating a number between 0 and the size of the words[] array. Random generates a float number so we need to cast it as an integer by wrapping random inside of int(). The. We can display that word on the screen: text(word, x, y); Where x and y are the coordinates of where you want to display. There are some ways to adjust textSize() as well as loading a textFont() but for now this is enough. More on reddit.com
🌐 r/processing
5
1
January 29, 2017
python - Getting a random word from a text file - Stack Overflow
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 lo... More on stackoverflow.com
🌐 stackoverflow.com
Pick a random big word from a list of words using Python - Code Review Stack Exchange
I am trying to randomly pick a large word (7 letters or more in length) from a large text file of words. I know that there has to be a better and more efficient way to do this. def goalWord(): ... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
December 30, 2017
How to select a random word from a txt file in python version 3.4? - Stack Overflow
Assuming each word is on a new line in file, you can read the text file into a list and use random.choice() to pick a random element in the list. Then you remove the word from the list so you don't pick it again. More on stackoverflow.com
🌐 stackoverflow.com
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 136320 › help-generate-random-word-function-from-fiveletter-txt-file
python - help! generate random word function from ... [SOLVED] | DaniWeb
You read the contents of the file into the variable t. At the very least you should be trying to use subscripts on t (even though that would still be wrong). randint returns a random integer, not a word.
🌐
Reddit
reddit.com › r/processing › selecting a random word from text file?
r/processing on Reddit: Selecting a random word from text file?
January 29, 2017 -

Hi, I'm tying to select a random word from a text file, display it, and then select another random word(and so on and so forth). I'm brand new to coding so VERY specific answers would be appreciated.

Top answer
1 of 3
4
The easiest way would be to use the split() function. Split() takes a string and returns an array of strings split up by user a character or string as a delimiter. In your case it would be very simple. String text = "Your text goes here."; String words[] = split(text, " "); This will however keep punctuation attached to any words. It may beyond your skill right now, but these sorts of problems are very easily solved by what is called a regular expression, or regex. As always, Shiffman has a pretty good video and guide on them. Essentially regex's are like using "find" in Word but on steroids. Edit: just realised this is only half the answer. To select a random word from our new words array we can simply do: String word = words[int(random(words.length))]; This might be a bit complicated looking at first but all we're doing is randomly generating a number between 0 and the size of the words[] array. Random generates a float number so we need to cast it as an integer by wrapping random inside of int(). The. We can display that word on the screen: text(word, x, y); Where x and y are the coordinates of where you want to display. There are some ways to adjust textSize() as well as loading a textFont() but for now this is enough.
2 of 3
3
I can't post code right now, on mobile, but my suggestion would be to write out the steps you want to have the program do. Then write the code for it. Parse your text file to look for words. (search for strings of characters between spaces, punctuation, etc) Put the words into a list-type structure. in Processing this would be an array, or an ArrayList. If you know how many words are in your document an array will work, because you declare its length when creating it. An ArrayList is much more flexible and can become longer or shorter. Select a random from your array. Because every word in your array will have an index number this can be done using the random() function with the array's length as its only argument. Display that word. If you want it to print to the console first, simply use the println() function. To display in a processing window, look into the typography section in the processing reference.
🌐
Bobby Hadz
bobbyhadz.com › blog › python-generate-random-word
How to generate random Words or Letters in Python | bobbyhadz
Copied!import random import requests def get_list_of_words(): response = requests.get( 'https://www.mit.edu/~ecprice/wordlist.10000', timeout=10 ) string_of_words = response.content.decode('utf-8') list_of_words = string_of_words.splitlines() return list_of_words words = get_list_of_words() print(words) random_word = random.choice(words) print(random_word) # 👉️ zoo ... If you don't have the requests module installed, install it by running the following command. ... Copied!# 👇️ In a virtual environment or using Python 2 pip install requests # 👇️ For python 3 (could also be pip3.10 depending on your version) pip3 install requests
🌐
Quora
quora.com › How-can-I-randomly-choose-a-line-from-a-TXT-file-in-Python-3
How to randomly choose a line from a TXT file in Python 3 - Quora
Answer (1 of 4): You don’t say how big the file is. If it is relatively small - read the whole file in (using readlines(), and then use random.choice() [code]import random def choose_line(file_name): """Choose a line at random from the text file""" with open(file_name, 'r') as file: lines ...
Top answer
1 of 7
15

Comments

  • Python functions are written in snake_case.
  • You could use function parameters for word length and filename.
  • You could use iterators and generators to avoid loading the whole file into memory.
  • If you read the file line by line, you need to take care with the trailing newline character: len("test\n") is 5.

Refactoring

Here's a way to rewrite your function. Thanks to a generator, the script only loops once over every line:

import random


def goal_word(min_length=7, filename="words.txt"):
    with open(filename) as wordbook:
        words = (line.rstrip('\n') for line in wordbook)
        large_words = [word for word in words if len(word) >= min_length]
    return random.choice(large_words)

print(goal_word(7))
# evening
print(goal_word(15))
# circumnavigations

Optimization

@etchesketch commented that rstrip is called on every line even though it's only needed for one word. Here's a variation:

import random


def goal_word(min_length=7, filename="words.txt"):
    min_line_length = min_length + 1
    with open(filename) as wordbook:
        large_words = [line for line in wordbook if len(line) >= min_line_length]
    return random.choice(large_words).rstrip('\n')

print(goal_word(7))
# jauntily
print(goal_word(15))
# fundamentalists

On a dictionary of English words (/usr/share/dict/american-english), this function is 3 times faster than the previous one.

Exception handling

In the above examples, goal_word(30) fails with IndexError: Cannot choose from an empty sequence. There's no indication that the desired length is too long.

Before calling random.choice, the script could simply check that large_words isn't empty:

import random


def goal_word(min_length=7, filename="words.txt"):
    min_line_length = min_length + 1
    with open(filename) as wordbook:
        large_words = [line for line in wordbook if len(line) >= min_line_length]
    if large_words:
        return random.choice(large_words).rstrip('\n')
    else:
        raise ValueError("No word found with at least %s characters." % min_length)


print(goal_word(7))
# jauntily
print(goal_word(15))
# insurrectionist's
print(goal_word(30))
# ValueError: No word found with at least 30 characters.
2 of 7
12

You don't need to read the whole file in at once nor use random.choice() if you use the reservoir-sampling algorithm. (This is the algorithm used in fortune on Unix!)

The algorithm is based on the idea that you select later samples based on a decreasing probability.

#!/usr/bin/python                                                               
import random                                                                   
from itertools import ifilter                                                   

_MAX_LEN = 6                                                                    

def goalword():                                                                 
    with open("words.txt") as fd:                                               
        for linenum, line in enumerate(ifilter(lambda x: len(x)-1 > _MAX_LEN, fd)):
            if random.uniform(0, linenum+1) <= 1:                                
                ret = line                                                      
    return ret.strip()                                                                  


print goalword()    

I based this on the Perl implementation from Perl Faq #5, which I'm more familiar with:

  srand;
  rand($.) < 1 && ($line = $_) while <>;

Since in Perl 0 <= rand(X) < X, whereas in Python, 0 <= random(0, X) <= X "depending on floating-point rounding in the equation a + (b-a) * random()", I've made my comparison inclusive (<=) to make sure the first line is always true.

If you look at Wikipedia's sample implementation, they just use randint(), so here is a modification to do that:

#!/usr/bin/python                                                               
from itertools import ifilter                                                   
from random import randint                                                      

_MAX_LEN = 6                                                                    

def goalword():                                                                 
    with open("words.txt") as fd:                                               
        for linenum, line in enumerate(ifilter(lambda x: len(x)-1 > _MAX_LEN, fd)):
            if randint(0, linenum) < 1:                                         
                ret = line                                                      
    return ret.strip()                                                                  


print goalword()           

Again, I make sure the first randint() is always true, otherwise a single line file might occasionally get no result.

For a reduce() implementation,

def goalword():                                                                
    with open("words.txt") as fd:                                               
        return reduce(lambda old, (i, new): new if randint(0, i) < 1 else old,
                      enumerate(ifilter(lambda x: len(x)-1 > _MAX_LEN, fd))).strip()

print goalword()  

Turns out, though, that reduce() isn't necessarily faster:

# for loop
print(timeit.timeit("goalword0()", setup="from __main__ import goalword0; import random; random.seed(42)", number=100, timer=time.clock))
# reduce
print(timeit.timeit("goalword1()", setup="from __main__ import goalword1; import random; random.seed(42)", number=100, timer=time.clock))

45.05 # for loop
49.17 # reduce

Note:

If you're picking more than one word from each execution, reading the whole file into a list will likely be more time efficient.

If you're just picking one word, however, this implementation is the most time and space efficient since you read the whole file once, but only retain one word in memory.

"In theory there is no difference between theory and practice. In practice there is."

I've tested this against a read-the-whole-file implementation:

def goalword():
    with open("words.txt") as fd:                                               
        words = filter(lambda x: len(x)-1 > _MAX_LEN, fd) 
    return random.choice(words).strip()                                         

It is significantly faster:

45.04 # For loop
7.14  # random.choice()

My word list is not insignificant:

$ curl -O https://raw.githubusercontent.com/dwyl/english-words/master/words.txt
$ wc -l words.txt 
466544 words.txt

My guess this is due to the overhead of the extra python opcode operations in the for loop vs filter being implemented in native C. i.e., we stay out of the interpreter for more of the work in the random.choice() implementation.

So, while not necessarily always faster, if you need to avoid loading the whole list into memory, reservoir sampling is what you want.

Find elsewhere
🌐
CopyProgramming
copyprogramming.com › howto › python-choose-random-words-from-file
Python: How to Choose and Select Random Words from Text Files - Choose and select random words from text files
October 30, 2025 - Understanding these methods, their trade-offs, and best practices will help you write more efficient and maintainable code in 2026. The simplest way to select a random word from a text file is using random.choice(), which returns a single random element from a sequence.
🌐
Reddit
reddit.com › r/learnpython › reading a random line from a text file
r/learnpython on Reddit: reading a random line from a text file
February 25, 2017 -

hey guys. i'm doing some homework. we are to write hangman. it seems like lots of people do it as there is tons of ways to do it. im working on my own, and i'm having trouble pulling a random line over from my wordList.txt I get no errors, but it's pulling over an empty string. here is mycode:

with open('wordList.txt', 'r') as wordList:      #open the file in readMode
    i=0
    for lines in wordList:                       #count the lines of the file to create a range for randint()
        i+=1
    wordSelect = random.randint(0,i)             #select a number within range of the number of lines in my wordList.txt
    secretWord = wordList.readlines(wordSelect)  #read the line(which is one word long)
print(wordSelect)                                #debuging: shows random number has been chosen
print(secretWord)                                #debugging prints"[]"

edit: thanks to u/commandlineuser for pointing out that after the for loop, there are no more lines to read. i updated my code to:

with open('wordList.txt', 'r') as wordList:              #open the file in readMode
    i=0                                                  #thanks to /u/commandlineuser for reminding me that after the loop, there are no more lines to read
    for lines in wordList:                               #count the lines of the file to create a range for randint()
        i+=1

with open('wordList.txt', 'r') as wordList:              #reopen the file
    wordSelect = random.randint(0,i)                     #use i from the previous open        
    secretWord = wordList.readlines()[wordSelect]        #get the line(which is one word 
🌐
Grabthiscode
grabthiscode.com › python › choice-random-word-in-python-from-a-text-file
Choice random word in python from a text file - code example - GrabThisCode.com
July 29, 2021 - Get code examples like"choice random word in python from a text file". Write more code and save time using our ready-made code examples.
🌐
Python Forum
python-forum.io › thread-34587.html
Generate a string of words for multiple lists of words in txt files in order.
August 11, 2021 - Ok, so I want to make something that takes some text files with lists of words in them and outputs every combination of those words in order. For example: If I had a txt file with the English dictionary, one with the names of the days and months, one...
🌐
Unix.com
unix.com › shell programming and scripting
Random word from a flat text file - Shell Programming and Scripting - Unix Linux Community
October 19, 2017 - Thanks echo table roof ceiling ... is the name of file that you select a random word num_words=\`wc -w $file_name | cut -d " " -f 1\` rand_word=\`expr "$RANDOM" % $num_words......
🌐
Reddit
reddit.com › r/learnpython › generate random word of specific length
r/learnpython on Reddit: Generate random word of specific length
November 15, 2022 -

I want to generate a random word of a specific length. I found a python module called random-word and this is my code.

from random_word import RandomWords
r = RandomWords()

# Return a single random word
r.get_random_word()

result = None
while result is None:
    try:
        word1 = r.get_random_word()
        print (word1)
        if len(word1) == 5:
            result = True
    except:
         print ('There was a problem')
# other code that uses result but is not involved in getting it

print (word1)
print (len(word1))

It works perfectly fine, but it's very slow. It takes about 10 to 15 seconds to run until it finds a word of that length. Does anybody have a better way of doing this? Another way I thought was to maybe have a dictionary file and iterate through that. The reason I don't like that approach is I don't really like the idea of having to have a file on the machine. Also if it iterates through the file it won't be random.

Any suggestions appreciated.

Thanks

🌐
Quora
quora.com › How-do-you-create-a-random-list-of-words-in-Python
How to create a random list of words in Python - Quora
Answer (1 of 3): t̲h̲i̲s̲ ̲d̲e̲m̲o̲n̲s̲t̲r̲a̲t̲e̲s̲ ̲-̲ ̲A̲l̲ri̲g̲h̲t̲ ̲,̲ ̲t̲o̲ c̲r̲e̲a̲t̲e̲ ̲a̲ ̲r̲a̲nd̲o̲m̲ ̲l̲i̲s̲t̲ ̲of̲ ̲w̲o̲rd̲s̲ ̲i̲n̲ ̲P̲y̲t̲h̲o̲n ̲,̲ ̲y̲o̲u̲’̲l̲l̲ ̲f̲i̲r̲s̲t ̲n̲e̲e̲d̲ ̲a̲ ̲s̲t̲a̲r̲t̲in̲g̲ ̲l̲i̲s̲t̲—l̲i̲k̲e̲ ̲`[̲'̲a̲p̲p̲l̲e̲'̲ ̲,̲ ̲'̲b̲a̲n̲a̲n̲a̲'̲ ̲,̲ ̲'̲c̲a̲r̲r̲o̲t̲'̲...
🌐
Reddit
reddit.com › r/c_programming › random word from text file
r/C_Programming on Reddit: Random Word From Text File
June 24, 2021 -

Hi there, I've been looking everywhere for a solution to this, however I can't find an answer written strictly in C. I have been trying to recreate Hangman in order to test myself, and I have a word file which I plan on expanding later. I would like to pick a random word from this list to use, but I can only figure out how to pick the first word. Any help would be really appreciated!