Reputation: 23941
This is a kind of newbie question, but I couldn't find a solution. I read a list of strings from a file, and try to get a random, 5 element sample with random.sample, but the resultung list only contains characters. Why is that? How can I get a random sample list of strings?
This is what I do:
names = random.sample( open('names.txt').read(), 5 )
print names
This gives a five element character list like:
['\x91', 'h', 'l', 'n', 's']
If I omit the random.sample part, and print the list, it prints out every line of the file, which is the expected behaviour, and proves that the file is read OK.
Upvotes: 2
Views: 404
Reputation: 81288
If the names are all on seperate lines, ry the following:
names = random.sample(open('names.txt').readlines(), count)
print names
Essentially you are going wrong because you need to pass an interable to random.sample()
. When you pass a string it treats it like a list. If you're names are all on one line, you need to use split()
to pull them apart and pass that list to random.sample()
.
Upvotes: 3