1

I'm trying to build a program that will pick a random items (just once for each) from a list, that was imported from a file. NB: I put only one item for a line in my file (no space, no coma, nothing else than a simple word)

I have a code like that for now:

file = open('file.txt', 'r')
myList = file.readlines()
myList[0]

rand_item = random.choice(myList)
print (rand_item)

I am just at the beginning of my program, so I'm just testing every new step that i make. Here, I'd like to display a random item from my list (itsefl imported from a file).

I have this message when I try to run my program:

Traceback (most recent call last):
  File "C:/Users/Julien/Desktop/test final.py", line 16, in <module>
    rand_item = random.choice(listEmployee)
AttributeError: 'builtin_function_or_method' object has no attribute 'choice'
pakfff
  • 11
  • 1
  • Did you do `from random import random`? – glibdud Dec 06 '17 at 22:05
  • Can you show the code how to import the `random`? – dkato Dec 06 '17 at 22:12
  • Please look at the `import` line in a following answer, carefully. https://stackoverflow.com/questions/306400/how-to-randomly-select-an-item-from-a-list – dkato Dec 06 '17 at 22:14
  • I'm sorry, I forgot to copy that... I did : from random import * (at the beginning of my code) – pakfff Dec 06 '17 at 22:49
  • Thanks dkato, I did the same, and it works now ! – pakfff Dec 07 '17 at 03:12
  • **1** You should close files when you've finished reading from them or writing to them. If you use a `with` statement the file will get closed automatically as soon as you exit the `with` block. **2** Since you want to choose items once only, you may find the `random.shuffle` function useful for your task. – PM 2Ring Dec 07 '17 at 05:03

0 Answers0