Manu Manjunath
Manu Manjunath

Reputation: 364

Can I print lines randomly from a csv in Python?

I'm trying print lines randomly from a csv.

Lets say the csv has the below 10 lines -

1,One
2,Two
3,Three
4,Four
5,Five
6,Six
7,Seven
8,Eight
9,Nine
10,Ten

If I write a code like below, it prints each line as a list in the same order as present in the CSV

import csv

with open("MyCSV.csv") as f:
    reader = csv.reader(f)
    for row_num, row in enumerate(reader):
        print(row)

Instead, I'd like it to be random.

Its just a print for now. I'll later pass each line as a List to a Function.

Upvotes: 0

Views: 81

Answers (5)

dijksterhuis
dijksterhuis

Reputation: 1271

Couple of things to do:

  1. Store CSV into a sequence of some sort
  2. Get the data randomly

For 1, it’s probably best to use some form of sequence comprehension (I’ve gone for nested tuple in a list as it seems you want the row numbers and we can’t use dictionaries for shuffle).

We can use the random module for number 2.

import random
import csv

with open("MyCSV.csv") as f:
    reader = csv.reader(f)
    my_csv = [(row_num, row) for row_num, row in enumerate(reader)]

# get only 1 item from the list at random
random_row = random.choice(my_csv)

# randomise the order of all the rows
shuffled_csv = random.shuffle(my_csv)

Upvotes: 0

Sawant Sharma
Sawant Sharma

Reputation: 758

import csv
import random
csv_elems = []

with open("MyCSV.csv") as f:
reader = csv.reader(f)
for row_num, row in enumerate(reader):
    csv_elems.append(row)

random.shuffle(csv_elems)
print(csv_elems[0])

As you can see I'm just printing the first elem, you can iterate over the list, keep shuffling & print

Upvotes: 1

Mohsen_Fatemi
Mohsen_Fatemi

Reputation: 3401

Well you can define a list, append all elements of csv file into it, then shuffle it and print them, assume that the name of this list is temp

 import csv
 import random
 temp = []

 with open("your csv file.csv") as file:
 reader = csv.reader(file)
 for row_num, row in enumerate(reader):
     temp.append(row)

 random.shuffle(temp)

 for i in range(len(temp)):
     print(temp[i])

Upvotes: 0

ImranD
ImranD

Reputation: 320

This should work. You can reuse the lines list in your code as it is shuffled.

import random

with open("tmp.csv", "r") as f:
    lines = f.readlines()

random.shuffle(lines)
print(lines)

Upvotes: 1

Alfonso
Alfonso

Reputation: 113

Why better don't you use pandas to handle csv?

import pandas as pd

data = pd.read_csv("MyCSV.csv")

And to get the samples you are looking for just write:

data.sample() # print one sample data.sample(5) # to write 5 samples

Also if you want to pass each line to a function. data_after_function = data.appy(function_name) and inside the function you can cast the line into a list with list()

Hope this helps!

Upvotes: 0

Related Questions