Reputation: 1
I have a .csv file with thankfully only two columns but many rows. Column 1 is a list of dates and column 2 is a list of numbers. One of the first things I have to do is tell how many months are in the dataset and the second thing is to find the total of all the numbers in column 2 (to then average etc).
i have tried making variables for each column and then using the sum function to no avail.
import os
import csv
budget_csv = os.path.join(".", "Resources", "budget_data.csv")
with open(budget_csv, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
csv_header = next(csvfile)
print(f"Header: {csv_header}")
total = 0
for row in csvreader:
totalPnl = total += int(x[1])
print(totalPnL)
I keep getting error messages, invalid syntax += for one. the two column headers do print out ok.
Upvotes: 0
Views: 74
Reputation: 20269
Your syntax is wrong - you're trying to assign the results of total += int(x[1])
to a variable called totalPnl
, which doesn't make any sense.
Instead, just increase the total
variable you already have:
import os
import csv
budget_csv = os.path.join(".", "Resources", "budget_data.csv")
with open(budget_csv, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
csv_header = next(csvfile)
print(f"Header: {csv_header}")
total = 0
for row in csvreader:
total += int(x[1])
print(total)
Upvotes: 1