-5

I'm trying to create a program that is able to randomly choose a name/ word from an external list such as .txt files however, I don't know how to import variables from an external list.

Thank You

glibdud
  • 7,550
  • 4
  • 27
  • 37
  • 2
    atleast try something. Search how to read file first. Then serach how to select random element from list python. – Poojan Oct 02 '19 at 17:09
  • 1
    https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list – Poojan Oct 02 '19 at 17:09
  • 1
    https://stackoverflow.com/questions/306400/how-to-randomly-select-an-item-from-a-list – Poojan Oct 02 '19 at 17:09
  • `random` module is the best bet here something like this`import random; random.choice([1,2,3,4])` – mad_ Oct 02 '19 at 17:12
  • I do know how to select random but don't know how to select from an external file. Thank You for the support guys. I manage to get it working. – Coding_Tutorials 2019 Oct 02 '19 at 17:20

1 Answers1

0

Pretty simple.

import random

inp = open("path/to/your/file/file.txt")
lines=inp.read().split("\n")
nLines = len(lines)
index = int(random.random()*nLines)
inp.close()

randLine = lines[index]
print(randLine)

now depending on the format of your input file you might need to parse things a little differently but this is an example for just grabbing a random line of text from a file.

Edit: as _mad points out you can use random.choice()

import random

inp = open("path/to/your/file/file.txt")
lines=inp.read().split("\n")
inp.close()

randLine = random.choice(lines)
print(randLine)
kpie
  • 9,588
  • 5
  • 28
  • 50