3

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 

1 Answer 1

4

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))
Sign up to request clarification or add additional context in comments.

4 Comments

Oo I'm sorry. I will edit the question. Thanks for your reply.
Since my csv file is small, there isn't much overhead reading whole file, but is there any way getting one element without reading it all?
I'm sorry for delay in approving and upvoting. Your answer worked well. Thank you.
@alireza thanks, BTW you cannot prevent it from reading the whole csv file.... however your code can be optimized but that's out of scope....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.