我需要获取 csv 中第二列的总和。我尝试了几种可能的解决方案,但最多只能得到 Totals = set{}
我希望获得从 csv 文件的第二列创建的列表的总和。我的 csv 文件如下所示:
我确信这一定是我所缺少的一个简单的解决方案,但我无法弄清楚,并且花了几个小时尝试我在此处和其他网站上找到的不同选项。我真的很感激任何帮助我指明正确方向的帮助。另外,为此,我不能使用 Pandas 这样的模块。这是我的代码。
import os
import csv
budget_csv = os.path.join("../PyBank", "budget_data.csv")
with open(budget_csv, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
#skip header row
next(csvreader, None)
# Gets number of rows in csv
data=list(csvreader)
row_count = len(data)
totals = []
for row in csvreader:
values = row[1]
totals.append(values)
print (totals) #did this just to see if it would print the list of values
print ("Financial Analysis")
print ("-------------------------------")
print ("Total Months: ", row_count)
print ("Total: ", sum(totals))
print ("Average Change: ")
print ("Greatest Increase in Profits: ")
print ("Greatest Decrease in Profits: ")
output_file = os.path.join("Analysis.txt")
# Open the output file
with open(output_file, "w") as text_file:
text_file.write (f"Financial Analysis\n")
text_file.write (f"-------------------------------\n")
text_file.write (f"Total Months: " + str(row_count) + "\n")
#print (f"Total: {}".format(net))
#print (f"Average Change: ")
#print (f"Greatest Increase in Profits: ")
#print (f"Greatest Decrease in Profits: ")
最佳答案
一旦 csvreader 转换为列表,您需要迭代数据,而不是 csvreader。
for row in data:
关于python - 如何获取要打印的 CSV 列列表的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53710235/