如何获取要打印的CSV列列表的总和

时间:2018-12-10 16:56:57

标签: python python-3.x csv sum

我需要获取csv中第二列的总和。我已经尝试了几种可能的解决方案,但是最多只能得到Totals = set{},在这里我希望从csv文件的第二列中获得我创建的列表的总和。我的csv文件如下所示:enter image description here

我确信它必须是我所缺少的简单解决方案,但我无法弄清楚,并花了数小时尝试在这里和其他站点上找到的其他选项。我真的很感谢您为我指明正确方向的任何帮助。另外,为此,我不能使用像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: ")  

3 个答案:

答案 0 :(得分:1)

将csvreader强制转换为列表后,您需要对数据进行迭代,而不是对csvreader进行迭代。

for row in data:

答案 1 :(得分:1)

终于明白了。创建了两个新变量。将totals = []重命名为totals1 = []。然后使用totals 1totals2 = [float(integral) for integral in totals1]中的整数转换为浮点数,该整数用来与totals3 = sum(totals2)求和。新代码:

     totals1 = [] for row in data:
         values = row[1] 
         totals1.append(values)          
     totals2 = [float(integral) for integral in totals1] #turns values in totals1 into floats
     totals3 = sum(totals2) 

答案 2 :(得分:0)

当您执行data=list(csvreader)时,您使用了csvreader,因此它位于文件的末尾,当您尝试在此行for row in csvreader:上对其进行再次迭代时,它为空,而total仍然为空清单。我也建议使用csv.DictReader。

未经测试,像

import os
import csv

budget_csv = os.path.join("../PyBank", "budget_data.csv")

with open(budget_csv, 'r') as csvfile:
    csvreader = csv.DictReader(csvfile, delimiter=",")
    totals = []
    for row_count, row in enumerate(csvreader, start=1):
        value = int(row['Profit/Losses'])
        totals.append(value)


print ("Financial Analysis")
print ("-------------------------------")
print ("Total Months: {}".format(row_count))
print ("Total: {}".format(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 ("Financial Analysis\n")
    text_file.write ("-------------------------------\n")
    text_file.write ("Total Months: {}\n".format(row_count))