I want to write a program that can randomly allocate seats. The name and the seat are in two columns of the CSV file, I want to randomly select them and print them. I will only read one column at random. How do I write two columns of data at random?

#read name column at random

with open('/home/name.csv', 'r') as fp:
     for l in fp:
      foo = list(fp)
      name = random.choice(foo)

#This is data in csv
column0  column1
Jacob      2A
Tony       3B
Emma       1C
Jack       5D
Ada        4A

Now i want to random choice Name and Place at same time and print it, but i don't know how to write it.

2 Answers

Devesh Kumar Singh On Best Solutions

You start by opening your csv file by using the csv module using csv.reader, read the rows and create your names and seats list, then randomly choose from both of them via random.choice

import csv
import random

names = []
seats = []
#Open csv file
with open('file.txt', 'r') as fp:
    #Read csv file
    reader = csv.reader(fp, delimiter=' ',skipinitialspace=True)
    #Skip header
    #Iterate through rows and create names and seats array
    for row in reader:

#Choose randomly from both of them
name = random.choice(names)
seat = random.choice(seats)

print(name, seat)

The output will look like

Tony 5D
Emma 1C

If you don't want to have two lists, you can instead read all rows via list-comprehension, and use zip to zip names and seats together.

Then the first tuple contains all names, and second tuple contains all seats, and you can randomly choose from them

import csv
import random

rows = []
#Open csv file
with open('file.txt', 'r') as fp:
    #Read csv file
    reader = csv.reader(fp, delimiter=' ',skipinitialspace=True)
    #Skip header
    #Iterate through rows, and zip names and seats together
    rows = list(zip(*[row for row in reader]))
    #[('Jacob', 'Tony', 'Emma', 'Jack', 'Ada'), ('2A', '3B', '1C', '5D', '4A')]

name = random.choice(rows[0])
seat = random.choice(rows[1])

print(name, seat)
vixrant On

This is my name.csv:

Jacob, 2A
Tony, 3B
Emma, 1C
Jack, 5D
Ada, 4A

First we need to import that data into a python data structure. The simplest would be a list of lists. You can also use pandas if you know that, but I'm using lists just to show you how to get started.

import csv
with open('name.csv') as f:
    reader = csv.reader(f)
    data = [row for row in reader]

Now my data variable is:

[['Jacob', ' 2A'],
 ['Tony', ' 3B'],
 ['Emma', ' 1C'],
 ['Jack', ' 5D'],
 ['Ada', ' 4A']]

Next, to choose a random row, I'll use random module of python to get a random row from the list of rows:

import random
random.choice(data) # Example output: ['Ada', ' 4A']

This will give me one of the rows from the table. You can select either of the 2 columns now.

name = random.choice(data)[0] # First column
seat = random.choice(data)[1] # Second column