# Calculate the average of the nth column (with 0 as the first column) of a csv file # This is somewhat more general than the task we did in class def IsFloat(sf): # return True if sf is a valid string representation of a floating-point number try: f = float(sf) return True except: return False def average_csv(filename, nth_column): # return the average (mean) of the numbers in the nth column of the requested csv file # return 0 if file is not readable or there's no data in the nth column # create a list of lines from reading the file try: f = open(filename,'r') except: return 0 lines = f.read().split('\n') f.close() # set up for calculating subtotal = 0 count = 0 # do it for aline in lines: words = aline.split(',') # check if the nth column exists and is a number if len(words) > nth_column: if IsFloat(words[nth_column]): subtotal += float(words[nth_column]) count += 1 if count > 0: return subtotal/count return 0