I need to add sums of a csv file. The program is a test for a travel reservation system and the file reads like this:
availableSTART,reservations,cancellations,availableEND
20,1,0,18
I need to subtract reservations from the available start integer, then add back cancellations (Which in this case results to 0) and then print the output, which in this case results in 18.
So far, I have opened the CSV file and printed what it contains.
Here is my code this far. Any help would be appreciated!
import csvwith open ('transactions.csv') as csvfile:readCSV = csv.reader(csvfile, delimiter=',')print (readCSV)for row in readCSV:print(row)
One way to read a CSV file is using a csv.DictReader.
This object can iterate your CSV file and return a dictionary which keys are columns names and values are row values.
But you need to convert string values to integers:
>>> import io
>>> import csv>>> with io.open('transactions.csv') as csvfile:
... reader = csv.DictReader(csvfile)
... for row in reader:
... values = {k: int(v) for k, v in row.items()}
... print(values)
...
{'availableEND': 18, 'reservations': 1, 'availableSTART': 20, 'cancellations': 0}
Then you can make your sums…
>>> with io.open('transactions.csv') as csvfile:
... reader = csv.DictReader(csvfile)
... for row in reader:
... values = {k: int(v) for k, v in row.items()}
... sums = values['availableSTART'] + values['cancellations'] - values['reservations']
... print(sums)
19