mrcoderman
mrcoderman

Reputation: 13

How to select a random value from a column in a CSV file in python?

So I am able to print out a full column from within a CSV easily with this code:

with open("compsci_questions.csv","r") as f:
        if difficulty=="easy":
            csv_reader=csv.reader(f)
            for line in csv_reader:
                print(line[0])

Which in turn returns:

What is the fastest type of storage?
Which register stores the results of calculations carried out by the ALU?
Which bus sends data to the CPU from the RAM?
What is 10110110 in denary?
What is 7D in denary?
In which topology is each computer connected individually to a central point?
What is half a byte known as?
What is 142 in binary?
What is each column known as in a record?
What is a variable which is available anywhere in a program known as?

How would I get it to randomly select just one of those questions as well as selecting the column?

Upvotes: 1

Views: 2530

Answers (1)

Stephen Rauch
Stephen Rauch

Reputation: 49822

You can use random.choice to get a random row in your csv like:

Code:

csv_reader = csv.reader(data)
questions = list(csv_reader)
random_question = random.choice(questions)

Note that this will return a list corresponds to the csv row. To get a specific column, you can then select like:

text = random_question[column_needed]

Test Code:

data = StringIO(u"""What is the fastest type of storage?
Which register stores the results of calculations carried out by the ALU?
Which bus sends data to the CPU from the RAM?
What is 10110110 in denary?
What is 7D in denary?
In which topology is each computer connected individually to a central point?
What is half a byte known as?
What is 142 in binary?
What is each column known as in a record?
What is a variable which is available anywhere in a program known as?""")

import random
import csv
csv_reader = csv.reader(data)
questions = list(csv_reader)
random_question = random.choice(questions)
print(random_question)

Results:

['What is 142 in binary?']

Upvotes: 2

Related Questions