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")
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()
.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With