Pulling a random word / line from a string in a text file in python

I have a text file with six words in one line, I need to randomly generate a word from this line. The text file name is WordsForGames.txt. I'm making an executioner. This is what I have, far away. I lost a little, 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")
+4
source share
4 answers

Your line words = open("../WordsForGames.txt")does not read the file, it simply opens it for reading or, possibly, writing, if you add additional flags.

You need, for example, to read a line or lines with readlines(), and then, most likely, break the words into a list, and then randomly select one of the words. Something like that:

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)
0

:

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

, .

( ), read() readline().

+2

.readline(), , . random.choice() .

with , with .

-

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)

, .read() .readline() ( ) -

with open("../WordsForGames.txt") as word_file:
        words = word_file.read().split()
+1

import random
print(random.choice(open('file.txt').read().split()).strip())
0
source

Source: https://habr.com/ru/post/1608914/


All Articles