Getting random element from a csv file

csv, python, python-3.x, random

Solution

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))

Problem

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 from`csv.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. EDIT: Every word is in a separated line like this: ``` when what make time ```

Original source