[Tutor] Instead of *.TXT I would like to use *.CSV exported from Excel

Peter Otten __peter__ at web.de
Fri Jul 4 09:21:52 CEST 2014


Mario Py wrote:

> OK, I'm finally getting closer.
> 
> Code bellow (looks like) works if I comment out shuffle part
> But I need it to shuffle so I get random picked words.
> 
> How do I get shuffle part to work?

csv.reader() returns an iterator, i. e. an object that dynamically 
calculates new rows on a next() call:

>>> f = open("tmp.csv")
>>> rows = csv.reader(f)
>>> next(rows)
['1', '2']
>>> next(rows)
['3', '4']

But shuffle() wants all items at once, in a "mutable sequence", an object 
with a length, whose items can be updated so that shuffle can swap items. 
The most common mutable sequence is a list, so

> from random import shuffle
> import csv
> 
> print('Write translation of Slovene word ')
> print()
> 
> out=open('c:\\prevedi.csv', 'r', newline='', encoding='utf8')
> data=csv.reader(out)

  data = list(data)
  shuffle(data)

> for line in data:
>      question, rightAnswer = line
>      answer = input(question + ' ')
>      if answer.lower() != rightAnswer:
>          print('Correct is: %s.' % rightAnswer,)
>          print()




More information about the Tutor mailing list