Random about a CSV in python?

-2

I want to get a row randomly from the 31 that my CSV file contains.

This is my code:

import csv 
import random 

path="/home/eocampo/Escritorio/porque_pregunta_6.csv" 
file=open(path,newline='') 
reader=csv.reader(file) 
data=[row for row in reader] 
reader = csv.reader(data[0], delimiter=',') 
i=0 
for row in reader: 
  print(row) 
  i=i+1 
  print(i) 
    
asked by Edgar Ocampo 25.05.2018 в 17:19
source

2 answers

0

Python is not my strong, but this I think could work for you:

import csv 
import random

path="/home/eocampo/Escritorio/porque_pregunta_6.csv" 
file=open(path,newline='') 
reader=csv.reader(file) 
data=[row for row in reader] 
reader = csv.reader(data[0], delimiter=',') 

contador = 0
total_de_lineas = sum(1 for row in reader)
linea_random = random.randint(0, total_de_lineas)
for row in reader:
  if linea_random == contador
    print(row)
    break
  contador = contador + 1
    
answered by 25.05.2018 в 17:47
0
import csv
import random

path="/home/eocampo/Escritorio/porque_pregunta_6.csv"
file=open(path,newline='')
reader=csv.reader(file)
data=[row for row in reader]
reader = csv.reader(data[0], delimiter=',')

randomList=[]
for row in reader:
    randomList.append(row)

newVar=random.choice(randomList)
print(newVar)

Colleagues, so I could solve it, my logic was to iterate on the csv, but no, create a new list loading all the csv and now I can apply the choice

    
answered by 25.05.2018 в 18:15