1

I want to have a list of names such as "john, jack, daniels, whisky, susan, alex" in a .txt file called 'names'.

Now, I want to import that file into my 'script' and use the import random module.

This is what I have:

import random

name = ( "jay" , "luis" , "bob" , "sofi", "susan" ) 

x = random.sample(name,input( "please enter the number of volunteers needed" ))
print x 

instead of having name = ( xxxxxxxxxxxxx ), I want to have name = .txt file.

Everytime i want to change the names I can just change it in the .txt file.

I'm trying to make a program for my schools volunteer club, so the number of volunteers chosen is at random and not biased. That way everyone has a somewhat fair chance. :]

1

5 Answers 5

3
file = open('myFile.txt', 'r')
names = file.read().split(',')
file.close()

Use that in place of your name = ... line and you should be good to go.

You can read more about reading and writing files in Python here.

Note that I assumed you'll have a comma-delimited list in the file. You can also put each name on a separate line and do names = file.readlines() instead.

Sign up to request clarification or add additional context in comments.

Comments

2

welcome to python :-]

how about something like this?

import random
fid = open('names.txt', 'r')
names = fid.readlines()

number_needed = raw_input('please enter the number of volunteers needed: ')

print random.sample(names, int(number_needed))

Comments

1

You could simply fill a text file with names delimited by line:

with open('names.txt') as f:
    names = f.read().splitlines()

Comments

0

Assuming a list of names in names.txt, one per line (and that you don't have a hundred million names in there):

import random
number_of_volunteers = 4
print random.sample([n[:-1] for n in open("./names.txt").readlines()], number_of_volunteers)

Comments

0

Where:

$ cat rand_nms.txt
jay
luis
bob
sofi

Then:

import random

contents=[]

with open("rand_nms.txt") as rnd:
    for line in rnd:
        line=line.strip()
        contents.append(line)

print contents
print "random name:", contents[random.randint(0,len(contents)-1)]

Result:

['jay', 'luis', 'bob', 'sofi', 'susan']
random name: luis

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.