Nick Charlton Nick Charlton - 1 month ago 9
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 = f.read()
f.close()
no_lines = x.split('\n') # remove lines
means = []
for i in no_lines:
no_commas = i.split(',') # remove commas
means.append(mean(no_commas))
return means


An example file of data is:

1,2
1,1,1,1
-1,0,1
42,17

Answer

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.

Comments