Nick Charlton Nick Charlton - 10 months ago 40
Python Question

averages of numbers in lines of data file "unsupported operand type(s) for +: 'int' and 'str'"

I'm trying to write some code that analyses a .csv file and then returns the average of the numbers on each line of the file as a list.

This is the code I have but I get this error which I don't understand!

def mean(values):
return sum(values) / len(values)

def line_averages(filename):
""" compute the average value for every line, and return the average
values in a list in the file "filename" """
f = open(filename, "r")
x =
no_lines = x.split('\n') # remove lines
means = []
for i in no_lines:
no_commas = i.split(',') # remove commas
return means

An example file of data is:


Answer Source

This is better done with the csv module. You can use the csv.reader method which takes a file object as parameter and whose default delimiter is a comma:

Here's one way to do it using a list comprehension with the csv.reader object:

import csv

def line_averages(filename):
    with open(filename) as f:
        reader = csv.reader(f)
        means = [sum(map(float, row))/len(row) for row in reader]
    return means

The with statement opens the file within a context and closes the file automatically once we move out of that context. You can wrap the list comp. in a try/except that handles ZeroDivisionError should in case there are rows with zero length in your file.