0
import csv

with open('scores.csv') as handle:
    reader = csv.reader(handle)
    for row in list(reader)[1:]:
        user, *scores = row
        average = sum([int(score) for score in scores]) / len(scores)
        print (
            "{user} has average of {average}".format(user=user,average=average)
        ) 

This code won't work in python 2.7 because of the *scores. How do I change this into python 2.7 as I don't know how?

This code was taken from this thread: Row Average CSV Python

jww
  • 97,681
  • 90
  • 411
  • 885
  • You'll also need to adjust the `average` line. In Python 3, `/` is "true division", but not in Python 2 -- the result will be truncated to an integer, instead. The simplest way would be by casting one of the values to a `float` first. – agf Apr 19 '15 at 08:40
  • Note that using `list(reader)[1:]` is hugely inefficient as that pulls everything in the file into a list. Use `next(reader, None)` on a separate line, then `for row in reader:` instead; that'll read one line from the CSV and discard it, effectively skipping that one row. See [Skip the headers when editing a csv file using Python](https://stackoverflow.com/a/14257599) – Martijn Pieters Apr 19 '15 at 08:43

2 Answers2

5

Change the line

user, *scores = row

to

user, scores = row[0], row[1:]

Note apart from the above, you should also change

average = sum([int(score) for score in scores]) / len(scores)

to

average = sum([int(score) for score in scores]) / float(len(scores))

as division in Python 2.X is integer division. Alternatively, you can also import real division from future

from __future__ import division

and to use integer division use double forward slash '//'

Abhijit
  • 62,056
  • 18
  • 131
  • 204
1

you should make our code so compatible with python 3 as possible, with future imports:

from __future__ import division, print_function
import csv

with open('scores.csv') as handle:
    reader = csv.reader(handle)
    next(reader) # header
    for row in reader:
        user = row[0]
        scores = row[1:]
        average = sum(int(score) for score in scores) / len(scores)
        print (
        "{user} has average of {average}".format(user=user, average=average)
        ) 
Daniel
  • 42,087
  • 4
  • 55
  • 81