Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting random element from a csv file

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.

EDIT:

Every word is in a separated line like this:

when  
what  
make  
time 
like image 435
Alireza Farahani Avatar asked Feb 14 '26 01:02

Alireza Farahani


1 Answers

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))
like image 57
K DawG Avatar answered Feb 15 '26 17:02

K DawG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!