Joshua Mitchell
Joshua Mitchell

Reputation: 21

Printing a random value from a .csv file

I am a teacher who is trying to create a program that will display students that are comfortable reading in class. They have filled out a form that populates a spreadsheet if they choose that they are comfortable.

I would like to randomly sort their names from the .csv, so that I get a single name each time I run the program. I keep getting an error that my file has no len().

Here is the code I have so far:

import csv
import random

with open('1st_period.csv', 'r') as student_csv_file:
    csv_reader = csv.reader(student_csv_file)

    next(csv_reader)
    #This skips over the first line in the .csv (first_name, last_name)

    for line in csv_reader:
        random.shuffle(csv_reader)
        print(line[0])

Here is my .csv file in same folder as the python file

first_name
Joshua
Jeremy
Mary
Martha

How can I do this correctly?

Upvotes: 0

Views: 2203

Answers (2)

mohd4482
mohd4482

Reputation: 1918

Try this code instead:

import csv
import random

with open("1st_period.csv", "r") as student_csv_file:
    csv_reader = csv.reader(student_csv_file)
    
    student_names = list(csv_reader)[1:]
    random.shuffle(student_names)

    for name in student_names:
        print(name)

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195543

Try random.choice instead of random.shuffle:

import csv
import random

with open("1st_period.csv", "r") as student_csv_file:
    csv_reader = csv.reader(student_csv_file)
    # This skips over the first line in the .csv (first_name, last_name)
    next(csv_reader)
    print(random.choice([line[0] for line in csv_reader]))

Prints (for example):

Jeremy

Upvotes: 1

Related Questions