Reputation: 109
I have a text file that has six words on one line, I need to randomly generate a word from that line. The text file name is WordsForGames.txt. I am making a hangman game. This what I have so, far. I am a little lost please help
import random
import os
print(" Welcome to the HangMan game!!\n","You will have six guesses to get the answer correct, or you will loose!!!",)
words = open("../WordsForGames.txt")
Upvotes: 6
Views: 31064
Reputation: 1
shortest solution
import random
print(random.choice(open('file.txt').read().split()).strip())
Upvotes: 0
Reputation: 881383
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()
.
Upvotes: 5
Reputation: 90889
You can read a line from the file using .readline()
function and then split the string into a list of strings, based on whatever delimiter you used for the the words in the line . And then random.choice()
to randomly select one word from the list.
Another suggestion would be to use with
statement for handling the file , so that with
statement can handle closing the file automatically for you.
Example -
import random
with open("../WordsForGames.txt") as word_file:
words = word_file.readline().split() #This splits by whitespace, if you used some other delimiter specify the delimiter here as an argument.
random_word = random.choice(words)
If the words are on separate lines, you can use .read()
instead of .readline()
as (with rest of the above logic same) -
with open("../WordsForGames.txt") as word_file:
words = word_file.read().split()
Upvotes: 2
Reputation: 10208
Your line words = open("../WordsForGames.txt")
does not read the file, it just opens it for reading or possibly writing if you add additional flags.
You need to read the line or lines using readlines()
, for example, and then most likely split the words into a list and then randomly select one of the words. Something like this:
import random
# get the first line if this is the one with the words words
lines = open("../WordsForGames.txt").readlines()
line = lines[0]
words = line.split()
myword = random.choice(words)
Upvotes: 2