Reputation: 29
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. :]
Upvotes: 1
Views: 6739
Reputation:
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
Upvotes: 0
Reputation: 2130
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))
Upvotes: 2
Reputation: 300
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)
Upvotes: 0
Reputation: 38778
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.
Upvotes: 3
Reputation: 53859
You could simply fill a text file with names delimited by line:
with open('names.txt') as f:
names = f.read().splitlines()
Upvotes: 1