Random row

37 views
Skip to first unread message

Dariusz Mysior

unread,
Dec 20, 2014, 4:37:23 PM12/20/14
to django...@googlegroups.com
Why I get only last row from my csv file, why I don't get in any time ranom row :/

import csv, random

def new_name():
   
with open('PL_surnames.csv', newline='') as csvfile:
        namesreader
= csv.reader(csvfile, delimiter=' ', quotechar='|')
       
for row in namesreader:
       
#print (','.join(row))
            random_choice
=random.choice(row)
   
return random_choice
print(new_name())


Cal Leeming

unread,
Dec 20, 2014, 4:42:32 PM12/20/14
to django...@googlegroups.com
Somewhat off-topic for django-users, this would have been better placed on StackOverflow.

If I understood your question correctly, I think you need to remove the "for row in namesreader" and replace with;

namesreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
return random.choice(row)

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/07b16c6a-ca3a-4b42-8c72-33981c05d317%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Cal Leeming

unread,
Dec 20, 2014, 4:42:36 PM12/20/14
to Cal Leeming, django...@googlegroups.com
Doh sorry, hit return too quickly.

return random.choice(namesreader)

m1chael

unread,
Dec 20, 2014, 4:42:47 PM12/20/14
to django...@googlegroups.com
you keep overwriting your random_choice every time the loop is run,
getting the last result is expected

Dariusz Mysior

unread,
Dec 20, 2014, 4:50:11 PM12/20/14
to django...@googlegroups.com
I change it on

import csv, random

def new_name():
   
with open('PL_surnames.csv', newline='') as csvfile:
        namesreader
= csv.reader(csvfile, delimiter=' ', quotechar='|')
       

        random_choice
=random.choice(namesreader)
   
return random_choice
print(new_name())



No I have this message

Traceback (most recent call last):
 
File "C:/Python31/csv", line 10, in <module>
   
print(new_name())
 
File "C:/Python31/csv", line 8, in new_name
    random_choice
=random.choice(namesreader*len(namesreader))
TypeError: object of type '_csv.reader' has no len()
>>>

Collin Anderson

unread,
Dec 22, 2014, 9:07:37 PM12/22/14
to django...@googlegroups.com
Hi,

Are you sure you saved your code? There's a len() in your traceback that isn't in your code.

Collin
Reply all
Reply to author
Forward
0 new messages