In: Computer Science
The file cereal.scsv contains the nutritional information for over 70 cereals. However it's in a format that is rarely used (semi-colon separated values). The reason it's in this format is that a few cereals have commas in their name (e.g. Fruit & Fibre Dates, Walnuts, and Oats). There is a separate lesson on converting this data to a proper csv format.
Also note that the first line identifies the column names; the second line identifies the data types for each column.
Part 1 reading and finding
Create
Create a function named find_total_for that has two parameters (in this order):
Read the data, parse the data
find_total_for will read in the file and sum up the values identified by column_name.
Notes and Hints:
Return
The function returns the sum of values for column column_name
(In Python)
The following function uses the simple concepts of file handling and split function to get the required information from the file. def find_total_for(filename_in,column_name): # Opening file as f f = open(filename_in) # Function to store all lines in a list rows = f.readlines() # To remove "\n" from end of each string for i in range(len(rows)-1): rows[i] = rows[i][:len(rows[i])-1]
# Counter of column c = 0 # Different column names given in first line columns = rows[0].split(";") # Getting the index of the required column for column in columns: if(column==column_name): req_column = c break c+=1 summ = 0 #Adding up the values from each row for i in range(1,len(rows)): col = rows[i].split(";") summ += int(col[req_column]) return summ