I have a Csv file containing many words. I want to write a python3 code that get a word from this file randomly. Since object returned fromcsv.reader(file) has no length parameter and isn't indexed, I have no idea how to get a word by random.
spamReader = csv.reader(open('A3_words.csv', 'r'))
# something like:
# rnd = random.randrange(reader.length)
# word = reader[rnd]
I would appriciate any help.
Every word is in a separated line like this:
when
what
make
time
This code would produce a random string from the sample you've provided
import csv
import random
spamReader = csv.reader(open('A3_words.csv', 'r'))
data = sum([i for i in spamReader],[]) #To flatten the list
print(random.choice(data))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With