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!
return sum(values) / len(values)
""" 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()
no_lines = x.split('\n') # remove lines
means = 
for i in no_lines:
no_commas = i.split(',') # remove commas
Here's one way to do it using a list comprehension with the
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
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.