Search code examples
pythontabular

Using an Excel table format in python


I have an Excel table saved as a CSV that looks something like (when it's in Excel) this just longer:

    Monday  Tuesday     Wednesday   Thursday    Friday
marsbar 9   8   0   6   5
reeses  0   0   0   9   0
twix    2   3   0   5   6
snickers    9   8   0   6   5

(The format isnt perfect, but you get the gist--candy bars/day). I want to write a program for python in which I could input a list of candy bar names in the program

>>> ['twix', 'reeses']

and it would give me the days of the week on which those candy bars were eaten and how many candy bars in the list were eaten on that day. The result would look something like this:

Monday 2
Tuesday 3
Wednesday 0
Thursday 14
Friday 6

could someone help me write such a program?


Solution

  • Your best bet is to use the csv package built into python. It will let you loop over the rows, giving you a list each time, like so:

    import csv
    candy_reader = csv.reader(open('candy.csv', 'rb'))
    
    for row in candy_reader:
      if row[0] in candy_to_find:
        monday_total += row[1]
        # etc.    
    

    I didn't initialize several variables, but I think this should give you the basic idea.